﻿using BinAnalysisHelp;

using HandyControl.Data;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace XChip_Tool_BinApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        public static List<BinBase> BinList;
        private ObservableCollection<USBDeviceModel> _usbDeviceList;
        public ObservableCollection<USBDeviceModel> USBDeviceList
        {
            get { return _usbDeviceList; }
            set
            {
                if (_usbDeviceList != value)
                {
                    _usbDeviceList = value;
                    OnPropertyChanged(nameof(USBDeviceList));
                }
            }
        }
        public bool IsLoad = false;

        private ManagementEventWatcher watcher;

        private Visibility isLoading ;
        public Visibility IsLoading
        {
            get { return isLoading; }
            set
            {
                isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        /// <summary>
        /// 定义选中的设备
        /// </summary>
        USBDeviceModel USBDeviceModelSelection = new USBDeviceModel();
        private Dictionary<int, byte> flippingMap = new Dictionary<int, byte>
{
    { 0, 0x3f },  // 标准正向
    { 1, 0x40 },  // 水平镜像
    { 2, 0x41 },  // 垂直镜像
    { 3, 0x42 }   // 旋转180°
};
        private bool IsMsgPrint = false;
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            Closed += MainWindow_Closed;
            this.DataContext = this;
            // 加载完成后隐藏 Loading 框
            
            RefreshParameterConfig();
            IsLoading = Visibility.Hidden;
            USBDeviceList = new ObservableCollection<USBDeviceModel>();
            UpdateUSBDevices();


         
        }
        /// <summary>
        /// 记录usb 是否打开的状态
        /// </summary>
        private bool IsUsbOpen { get; set; } = false;

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            // 在窗口关闭时停止监视 USB 事件
            watcher?.Stop();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            // 创建 WMI 查询语句，用于监视 USB 设备的连接和断开事件
            var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2 or EventType = 3");

            // 创建 ManagementEventWatcher 对象，用于监视 WMI 事件
            watcher = new ManagementEventWatcher(query);
            watcher.EventArrived += USBEventArrived;
            watcher.Start();
        }

        /// <summary>
        /// 显示错误信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowErrorMessage(string message,int time = 3000)
        {
            HandyControl.Controls.Growl.Error(new GrowlInfo()
            {
                Message = message,
                Token = "ErrorMsg",
                ShowCloseButton = true,
                ShowDateTime = true
            });
            Task.Delay(time).ContinueWith(_ =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    HandyControl.Controls.Growl.Clear("ErrorMsg");
                });
            });
        }
        /// <summary>
        /// 显示正确信息
        /// </summary>
        /// <param name="message"></param>
        private void ShowSuccessMessage(string message,int time=3000)
        {
            HandyControl.Controls.Growl.Success(new GrowlInfo()
            {
                Message = message,
                Token = "SuccessMsg",
                ShowCloseButton = true,
                ShowDateTime = true
            });
            Task.Delay(time).ContinueWith(_ =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    HandyControl.Controls.Growl.Clear("SuccessMsg");
                });
            });
        }

        private void USBEventArrived(object sender, EventArrivedEventArgs e)
        {
            var eventType = (ushort)e.NewEvent.Properties["EventType"].Value;

            if (eventType == 2) // USB 连接事件
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    
                        UpdateUSBDevices();
                    
                    
                    

                    //shebei.ItemsSource = UsbDeviceList;

                    if (_usbDeviceList.Count > 0)
                    {
                        USBDeviceModelSelection = _usbDeviceList[(shebei.SelectedIndex == -1?0: shebei.SelectedIndex)];
                        if (!USBDeviceModelSelection.IsOpen)
                        {
                            GetDeviceInfo(USBDeviceModelSelection.DeviceNum);
                        }
                    }
                });
            }
            else if (eventType == 3) // USB 断开事件
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    // 清空文本值显示
                    DeviceVid.Text = string.Empty;
                    DevicePid.Text = string.Empty;
                    DeviceVer.Text = string.Empty;
                    DeviceName.Text = string.Empty;
                    DeviceiManufacture.Text = string.Empty;
                    DeviceiSerialNumber.Text = string.Empty;
                   

                    USBDeviceList.Clear();

                    UpdateUSBDevices();
                    IsUsbOpen = false;
                    //shebei.ItemsSource = _usbDeviceList;
                });
            }
        }

        private void RefreshParameterConfig()
        {
            BRIGHTNESS_Slider.Minimum =Convert.ToInt32( PuctHelp.PU_BRIGHTNESS_CONTROL.min_val,16);
            BRIGHTNESS_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_BRIGHTNESS_CONTROL.max_val, 16);

            CONTRAST_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_CONTRAST_CONTROL.min_val, 16);
            CONTRAST_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_CONTRAST_CONTROL.max_val, 16);

            HUE_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_HUE_CONTROL.min_val, 16);
            HUE_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_HUE_CONTROL.max_val, 16);

            SATURATION_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_SATURATION_CONTROL.min_val, 16);
            SATURATION_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_SATURATION_CONTROL.max_val, 16);

            SHARPNESS_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_SHARPNESS_CONTROL.min_val, 16);
            SHARPNESS_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_SHARPNESS_CONTROL.max_val, 16);

            GAMMA_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_GAMMA_CONTROL.min_val, 16);
            GAMMA_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_GAMMA_CONTROL.max_val, 16);

            BALANCE_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.min_val, 16);
            BALANCE_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.max_val, 16);

            Backlight_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.min_val, 16);
            Backlight_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.max_val, 16);

            GAIN_Slider.Minimum = Convert.ToInt32(PuctHelp.PU_GAIN_CONTROL.min_val, 16);
            GAIN_Slider.Maximum = Convert.ToInt32(PuctHelp.PU_GAIN_CONTROL.max_val, 16);

            ZOOM_Slider.Minimum = Convert.ToInt32(PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.min_val, 16);
            ZOOM_Slider.Maximum = Convert.ToInt32(PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.max_val, 16);

            FOCUS_Slider.Minimum = Convert.ToInt32(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.min_val, 16);
            FOCUS_Slider.Maximum = Convert.ToInt32(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.max_val, 16);

            EXPOSURE_Slider.Minimum = Convert.ToInt64(PuctHelp.CT_AE_MODE_CONTROL.min_val, 16);
            EXPOSURE_Slider.Maximum = Convert.ToInt32(PuctHelp.CT_AE_MODE_CONTROL.max_val, 16);

            Panorama_Slider.Minimum = Convert.ToInt32(PuctHelp.Panorama.min_val, 16);
            Panorama_Slider.Maximum = Convert.ToInt32(PuctHelp.Panorama.max_val, 16);

            Tilt_Slider.Minimum = Convert.ToInt32(PuctHelp.Tilt.min_val, 16);
            Tilt_Slider.Maximum = Convert.ToInt32(PuctHelp.Tilt.max_val, 16);

            Rolling_Slider.Minimum = Convert.ToInt32(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.min_val, 16);
            Rolling_Slider.Maximum = Convert.ToInt32(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.max_val, 16);



        }

        private void UpdateProgressBar(double newValue)
        {
            // 确保值在有效范围内  
            if (newValue < 0 || newValue > 100)
                return;

            // 在UI线程上更新ProgressBar的值  
            Application.Current.Dispatcher.Invoke(() =>
            {
                progressBar.Value = newValue; // 更新ProgressBar的值  
            });

        }

        /// <summary>
        /// 刷新USB设备信息
        /// </summary>
        /// <returns></returns>
        private void UpdateUSBDevices()
        {
            int num = 0;
            IntPtr devicebool;

            if (IntPtr.Size == 8)
            {
                XChipUSB.UsbIniDevice64();
                XChipUSB.UsbUpdateDevice64();
                num = XChipUSB.UsbGetDeviceNum64();
                devicebool = XChipUSB.UsbGetAllDeviceInfo64();
            }
            else
            {
                XChipUSB.UsbIniDevice86();
                XChipUSB.UsbUpdateDevice86();
                num = XChipUSB.UsbGetDeviceNum86();
                devicebool = XChipUSB.UsbGetAllDeviceInfo86();
            }
            
                

            DeviceInfo[] deviceInfoArray = new DeviceInfo[num];
            for (int i = 0; i < deviceInfoArray.Length; i++)
            {
                DeviceInfo deviceInfo = new DeviceInfo();
                var one = (i * 120) * 2 + (i * 8);
                deviceInfo.DevicePath = Marshal.PtrToStringAnsi(devicebool + one, 120);
                var two = (i * 120) * 2 + 120 + (i * 8);
                deviceInfo.DeviceName = Marshal.PtrToStringAnsi(devicebool + two, 120);
                var three = (i * 120) * 2 + 240 + (i * 8);
                deviceInfo.PID = Marshal.PtrToStringAnsi(devicebool + three, 4);
                var four = (i * 120) * 2 + 240 + 4 + (i * 8);
                deviceInfo.VID = Marshal.PtrToStringAnsi(devicebool + four, 4);
                deviceInfo.DeviceNum = i;
                if (IntPtr.Size == 8)
                {
                    XChipUSB.UsbSelectDevice64(i);
                    uint temp0 = (uint)ReadRegister(BinHelp.Bin151,false);
                    uint temp1 = (uint)ReadRegister(BinHelp.Bin151 + 1, false);
                    uint temp2 = (uint)ReadRegister(BinHelp.Bin151 + 2, false);
                    uint temp3 = (uint)ReadRegister(BinHelp.Bin151 + 3, false);
                    if (temp0 == 0x51 && temp1 == 0x01 && temp2 == 0x43 && temp3 == 0x58)
                    {
                        deviceInfoArray[i] = deviceInfo;
                    }
                }
                else
                {
                    XChipUSB.UsbSelectDevice86(i);
                    uint temp0 = (uint)ReadRegister(BinHelp.Bin151, false);
                    uint temp1 = (uint)ReadRegister(BinHelp.Bin151 + 1, false);
                    uint temp2 = (uint)ReadRegister(BinHelp.Bin151 + 2, false);
                    uint temp3 = (uint)ReadRegister(BinHelp.Bin151 + 3, false);
                    if (temp0 == 0x51 && temp1 == 0x01 && temp2 == 0x43 && temp3 == 0x58)
                    {
                        deviceInfoArray[i] = deviceInfo;
                    }
                }
               
            }
            //添加判断  _usbDeviceList是否存在deviceInfoArray的数据  存在 则不进行下面操作
            if (null ==_usbDeviceList || _usbDeviceList.Any(d => deviceInfoArray.Any(di => di.DevicePath == d.DevicePath &&di.DeviceNum == d.DeviceNum)))
            {
                return;
            }
            string usbPath = string.Empty;
            if (_usbDeviceList.Any(c => c.IsOpen))
            {
                usbPath = _usbDeviceList.First(c => c.IsOpen).DevicePath;
            }

            var newDevices = deviceInfoArray
                .Where(d => !string.IsNullOrEmpty(d.PID) && !string.IsNullOrEmpty(d.VID) && d.PID != "\0\0\0\0" && d.VID != "\0\0\0\0")
                .Select((d, i) => new USBDeviceModel()
                {
                    DeviceName = d.DeviceName,
                    PID = d.PID,
                    VID = d.VID,
                    DevicePath = d.DevicePath,
                    Index = i,
                    DeviceNum = d.DeviceNum,
                    IsOpen = !string.IsNullOrEmpty(usbPath) && d.DevicePath == usbPath
                });

            _usbDeviceList.Clear();

            foreach (var newDevice in newDevices)
            {
                if (!_usbDeviceList.Any(d => d.DevicePath == newDevice.DevicePath))
                {
                    _usbDeviceList.Add(newDevice);
                }
            }
        }

        /// <summary>
        /// 加载程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void LoadProgramBtn_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "导入BIN（*.bin）|*.bin";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() != true) return;
            IsLoading = Visibility.Visible;
            PuctHelp.InitializePuctModels();



            await Task.Run(() =>
            {
                
                    try
                    {

                        LoadProgram(sfd.FileName);
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        LoadTxt1.Text = sfd.FileName;
                    });
                    

                        ShowSuccessMessage($"加载程序完成！");

                    }
                    catch (Exception ex)
                    {
                        ShowErrorMessage(ex.Message.ToString());
                    }
                    

               
            });

            // 异步操作完成后隐藏加载指示器
            IsLoading = Visibility.Hidden;
           



        }


        private void LoadProgram(string fileName)
        {
            IsLoad = true;
            InitMethod();
            UpdateProgressBar(0);
            BinList = LoadBinList(fileName);
            UpdateUserInterface(BinList);
            
           
            UpdateProgressBar(100);
            IsLoad = false;


            _ = Task.Delay(3000).ContinueWith(_ =>
              {
                  Application.Current.Dispatcher.Invoke(() =>
                  {
                      UpdateProgressBar(0);
                  });
              });
        }
        private List<BinBase> LoadBinList(string fileName)
        {
            UpdateProgressBar(10);
            var binList = BinHelp.BinToList(fileName);
            var xclist = JsonConvert.DeserializeObject<List<xc151binparsing>>(AESExample.DecryptString(xc151.xc151Str)).OrderBy(c => c.Id).ToList();
            BinHelp.BinBaseToNode(binList, xclist);
            UpdateProgressBar(20);
            binList = BinHelp.BinBaseToIsp(binList);
            UpdateProgressBar(30);
            BinHelp.SetModeIsp(ref binList);
            UpdateProgressBar(40);
            SettingPUCT.SetPuct(binList);
            string binName = string.Empty;
            BinHelp.GetBinName(binList,out binName);
            Application.Current.Dispatcher.Invoke(() =>
            {
                fwName.Text = UserFwName.Text = binName;
            });
            
            UpdateProgressBar(50);
            return binList;
        }
        private void UpdateUserInterface(List<BinBase> binList)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                //处理文本显示
                UserVid.Text = FirmwareVid.Text = PuctHelp.userParametersUsb.VidNumber.ToString("X4");
                UserPid.Text = FirmwarePid.Text = PuctHelp.userParametersUsb.PidNumber.ToString("X4");
                UserDevice.Text = FirmwareDeviceName.Text = PuctHelp.userParametersUsb.VideoName;
                UserManufacture.Text = FirmwareiManufacture.Text = PuctHelp.userParametersUsb.ManufactureName;
                UserSerialNumber.Text = FirmwareiSerialNumber.Text = PuctHelp.userParametersUsb.SerialNumberName;
                UserMic.Text = PuctHelp.userParametersUsb.VideoMicName;
                UserVer.Text = FirmwareVer.Text = PuctHelp.userParametersUsb.UserVerName;



                UpdateProgressBar(60);
                //参数设置
                var count = PuctHelp.userParametersUsb.VideoCPResult.Count();
                if (count == PuctHelp.userParametersUsb.VideoCPResult[0].original)
                {
                    if (PuctHelp.userParametersUsb.VideoCPResult[7].original == 0x0)
                    {
                        IS_BRIGHTNESS.IsEnabled = false;//D0：亮度
                        IS_CONTRAST.IsEnabled = false;//D1：对比度
                        IS_HUE.IsEnabled = false;//D2：色调
                        IS_SATURATION.IsEnabled = false;//D3：饱和
                        IS_SHARPNESS.IsEnabled = false;//D4：锐度
                        IS_GAMMA.IsEnabled = false;//D5：伽马射线
                        IS_BALANCE.IsEnabled = false;//D6：白平衡温度
                        IS_Backlight.IsEnabled = false;//D8：背光补偿
                        IS_GAIN.IsEnabled = false;//D9：增益
                        AutoWhiteBalance.IsEnabled = false;//D12：白平衡温度，自动
                        POWER_LINE_Combox.IsEnabled = false;
                    }
                    else if (PuctHelp.userParametersUsb.VideoCPResult[7].original == 0x1)
                    {
                        var bmControls1 = PuctHelp.userParametersUsb.VideoCPResult[8];
                        IS_BRIGHTNESS.IsEnabled = ((bmControls1.original & 0x1) == 0x1) && (PuctHelp.IsPuct || PuctHelp.PU_BRIGHTNESS_CONTROL.def_bool);//D0：亮度
                        IS_CONTRAST.IsEnabled = ((bmControls1.original & 0x2) == 0x2) && (PuctHelp.IsPuct || PuctHelp.PU_CONTRAST_CONTROL.def_bool);//D1：对比度
                        IS_HUE.IsEnabled = ((bmControls1.original & 0x4) == 0x4) && (PuctHelp.IsPuct || PuctHelp.PU_HUE_CONTROL.def_bool);//D2：色调
                        IS_SATURATION.IsEnabled = ((bmControls1.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.PU_SATURATION_CONTROL.def_bool);//D3：饱和
                        IS_SHARPNESS.IsEnabled = ((bmControls1.original & 0x10) == 0x10) && (PuctHelp.IsPuct || PuctHelp.PU_SHARPNESS_CONTROL.def_bool);//D4：锐度
                        IS_GAMMA.IsEnabled = ((bmControls1.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.PU_GAMMA_CONTROL.def_bool);//D5：伽马射线
                        IS_BALANCE.IsEnabled = ((bmControls1.original & 0x40) == 0x40) && (PuctHelp.IsPuct || PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_bool);//D6：白平衡温度
                    }
                    else if (PuctHelp.userParametersUsb.VideoCPResult[7].original == 0x2)
                    {
                        var bmControls1 = PuctHelp.userParametersUsb.VideoCPResult[8];
                        var bmControls2 = PuctHelp.userParametersUsb.VideoCPResult[9];
                        IS_BRIGHTNESS.IsEnabled = ((bmControls1.original & 0x1) == 0x1) && (PuctHelp.IsPuct || PuctHelp.PU_BRIGHTNESS_CONTROL.def_bool);//D0：亮度
                        IS_CONTRAST.IsEnabled = ((bmControls1.original & 0x2) == 0x2) && (PuctHelp.IsPuct || PuctHelp.PU_CONTRAST_CONTROL.def_bool);//D1：对比度
                        IS_HUE.IsEnabled = ((bmControls1.original & 0x4) == 0x4) && (PuctHelp.IsPuct || PuctHelp.PU_HUE_CONTROL.def_bool);//D2：色调
                        IS_SATURATION.IsEnabled = ((bmControls1.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.PU_SATURATION_CONTROL.def_bool);//D3：饱和
                        IS_SHARPNESS.IsEnabled = ((bmControls1.original & 0x10) == 0x10) && (PuctHelp.IsPuct || PuctHelp.PU_SHARPNESS_CONTROL.def_bool);//D4：锐度
                        IS_GAMMA.IsEnabled = ((bmControls1.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.PU_GAMMA_CONTROL.def_bool);//D5：伽马射线
                        IS_BALANCE.IsEnabled = ((bmControls1.original & 0x40) == 0x40) && (PuctHelp.IsPuct || PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_bool);//D6：白平衡温度
                        IS_Backlight.IsEnabled = ((bmControls2.original & 0x1) == 0x1) && (PuctHelp.IsPuct || PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.def_bool);//D8：背光补偿
                        IS_GAIN.IsEnabled = ((bmControls2.original & 0x2) == 0x2) && (PuctHelp.IsPuct || PuctHelp.PU_GAIN_CONTROL.def_bool);//D9：增益
                        IsPOWER_LINE.IsEnabled = ((bmControls2.original & 0x4)) == 0x4;//D10：电源线频率 
                        AutoWhiteBalance.IsEnabled = (bmControls2.original & 0x10) == 0x10;//D12：白平衡温度，自动
                    }
                    else if (PuctHelp.userParametersUsb.VideoCPResult[7].original == 0x2)
                    {
                        var bmControls1 = PuctHelp.userParametersUsb.VideoCPResult[8];
                        var bmControls2 = PuctHelp.userParametersUsb.VideoCPResult[9];
                        var bmControls3 = PuctHelp.userParametersUsb.VideoCPResult[10];
                        IS_BRIGHTNESS.IsEnabled = ((bmControls1.original & 0x1) == 0x1) && (PuctHelp.IsPuct || PuctHelp.PU_BRIGHTNESS_CONTROL.def_bool);//D0：亮度
                        IS_CONTRAST.IsEnabled = ((bmControls1.original & 0x2) == 0x2) && (PuctHelp.IsPuct || PuctHelp.PU_CONTRAST_CONTROL.def_bool);//D1：对比度
                        IS_HUE.IsEnabled = ((bmControls1.original & 0x4) == 0x4) && (PuctHelp.IsPuct || PuctHelp.PU_HUE_CONTROL.def_bool);//D2：色调
                        IS_SATURATION.IsEnabled = ((bmControls1.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.PU_SATURATION_CONTROL.def_bool);//D3：饱和
                        IS_SHARPNESS.IsEnabled = ((bmControls1.original & 0x10) == 0x10) && (PuctHelp.IsPuct || PuctHelp.PU_SHARPNESS_CONTROL.def_bool);//D4：锐度
                        IS_GAMMA.IsEnabled = ((bmControls1.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.PU_GAMMA_CONTROL.def_bool);//D5：伽马射线
                        IS_BALANCE.IsEnabled = ((bmControls1.original & 0x40) == 0x40) && (PuctHelp.IsPuct || PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_bool);//D6：白平衡温度
                        IS_Backlight.IsEnabled = ((bmControls2.original & 0x1) == 0x1) && (PuctHelp.IsPuct || PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.def_bool);//D8：背光补偿
                        IS_GAIN.IsEnabled = ((bmControls2.original & 0x2) == 0x2) && (PuctHelp.IsPuct || PuctHelp.PU_GAIN_CONTROL.def_bool);//D9：增益
                        IsPOWER_LINE.IsEnabled = ((bmControls2.original & 0x4)) == 0x4;//D10：电源线频率
                        AutoWhiteBalance.IsEnabled = (bmControls2.original & 0x10) == 0x10;//D12：白平衡温度，自动

                    }



                }



                UpdateProgressBar(70);
                count = PuctHelp.userParametersUsb.VideoCIResult.Count();
                if (count == PuctHelp.userParametersUsb.VideoCIResult[0].original)
                {

                    if (PuctHelp.userParametersUsb.VideoCIResult[14].original == 0x0)
                    {
                        AutoExposure.IsEnabled = false;//D1：自动曝光模式
                        IS_EXPOSURE.IsEnabled = false;//D3：曝光时间（绝对值）
                        IS_FOCUS.IsEnabled = false;//D5：焦点（绝对）
                        AutoFocus.IsEnabled = false;//D17：自动对焦
                    }
                    else if (PuctHelp.userParametersUsb.VideoCIResult[14].original == 0x1)
                    {
                        var bmControls4 = PuctHelp.userParametersUsb.VideoCIResult[15];
                        AutoExposure.IsEnabled = (bmControls4.original & 0x2) == 0x2;//D1：自动曝光模式
                        IS_EXPOSURE.IsEnabled = ((bmControls4.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.CT_AE_MODE_CONTROL.def_bool);//D3：曝光时间（绝对值）
                        IS_FOCUS.IsEnabled = ((bmControls4.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_bool);//D5：焦点（绝对）
                    }
                    else if (PuctHelp.userParametersUsb.VideoCIResult[14].original == 0x2)
                    {
                        var bmControls4 = PuctHelp.userParametersUsb.VideoCIResult[15];
                        var bmControls5 = PuctHelp.userParametersUsb.VideoCIResult[16];
                        AutoExposure.IsEnabled = (bmControls4.original & 0x2) == 0x2;//D1：自动曝光模式
                        IS_EXPOSURE.IsEnabled = ((bmControls4.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.CT_AE_MODE_CONTROL.def_bool);//D3：曝光时间（绝对值）
                        IS_FOCUS.IsEnabled = ((bmControls4.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_bool);//D5：焦点（绝对）
                        IS_Rolling.IsEnabled = ((bmControls5.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.def_bool);//D13: 滚动（绝对）                                                                                                                  //var d7 = (bmControls4.original & 0x80) == 0x80;//D7：虹膜光圈（绝对）


                    }
                    else if (PuctHelp.userParametersUsb.VideoCIResult[14].original == 0x3)
                    {
                        var bmControls4 = PuctHelp.userParametersUsb.VideoCIResult[15];
                        var bmControls5 = PuctHelp.userParametersUsb.VideoCIResult[16];
                        var bmControls6 = PuctHelp.userParametersUsb.VideoCIResult[17];

                        //var d0 = (bmControls4.original & 0x1) == 0x1;//D0：扫描模式 //扫描模式(逐行扫描或隔行扫描)
                        AutoExposure.IsEnabled = (bmControls4.original & 0x2) == 0x2;//D1：自动曝光模式
                        IS_EXPOSURE.IsEnabled = ((bmControls4.original & 0x8) == 0x8) && (PuctHelp.IsPuct || PuctHelp.CT_AE_MODE_CONTROL.def_bool);//D3：曝光时间（绝对值）
                        IS_FOCUS.IsEnabled = ((bmControls4.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_bool);//D5：焦点（绝对）
                        IS_Rolling.IsEnabled = ((bmControls5.original & 0x20) == 0x20) && (PuctHelp.IsPuct || PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.def_bool);//D13: 滚动（绝对）                                                                                                                  //var d7 = (bmControls4.original & 0x80) == 0x80;//D7：虹膜光圈（绝对）

                        AutoFocus.IsEnabled = (bmControls6.original & 0x2) == 0x2;//D17：自动对焦
                    }


                }

                if (PuctHelp.IsPuct)
                {
                    if (Convert.ToUInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 白平衡")).valH}{PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 白平衡")).valL}", 16) != 0x0)
                    {
                        AutoWhiteBalance.IsChecked = true;
                    }
                    if (Convert.ToUInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_AUTO_CONTROL 焦点自动控制")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_AUTO_CONTROL 焦点自动控制")).valL}", 16) != 0x0)
                    {
                        AutoFocus.IsChecked = true;
                    }
                    if (Convert.ToUInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("CT_AE_MODE_CONTROL AE_MODE控制")).valH}{PuctHelp.Parameters.First(c => c.Note.Contains("CT_AE_MODE_CONTROL AE_MODE控制")).valL}", 16) != 0x1)
                    {
                        AutoExposure.IsChecked = true;
                    }
                }
                else
                {
                    if (PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL.def_val != "-1")
                    {
                        if (PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL.def_val.Contains("1"))
                        {
                            AutoWhiteBalance.IsChecked = true;
                        }
                    }
                    if (PuctHelp.CT_FOCUS_AUTO_CONTROL.def_val != "-1")
                    {
                        if (PuctHelp.CT_FOCUS_AUTO_CONTROL.def_val.Contains("1"))
                        {
                            AutoFocus.IsChecked = true;
                        }
                    }
                    if (PuctHelp.CT_AE_MODE_AUTO_CONTROL.def_val != "-1")
                    {
                        if (PuctHelp.CT_AE_MODE_AUTO_CONTROL.def_val.Contains("2"))
                        {
                            AutoExposure.IsChecked = true;
                        }
                    }
                }


                UpdateProgressBar(80);

                //// 缩放
                IS_ZOOM.IsEnabled = false;
                // 全景
                IS_Panorama.IsEnabled = false;

                // 倾斜
                IS_Tilt.IsEnabled = false;

                // 滚动
                //IS_Rolling.IsEnabled = false;

                //设置值
                if (PuctHelp.IsPuct)
                {
                    if (IS_BRIGHTNESS.IsEnabled)
                    {
                        BRIGHTNESS_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_BRIGHTNESS_CONTROL 亮度")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_BRIGHTNESS_CONTROL 亮度")).valL}", 16);

                    }
                    if (IS_CONTRAST.IsEnabled)
                    {
                        CONTRAST_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_CONTRAST_CONTROL 对比度")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_CONTRAST_CONTROL 对比度")).valL}", 16);

                    }
                    if (IS_HUE.IsEnabled)
                    {
                        HUE_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_HUE_CONTROL 色调")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_HUE_CONTROL 色调")).valL}", 16);

                    }
                    if (IS_SATURATION.IsEnabled)
                    {
                        SATURATION_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_SATURATION_CONTROL 饱和度")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_SATURATION_CONTROL 饱和度")).valL}", 16);

                    }
                    if (IS_SHARPNESS.IsEnabled)
                    {
                        SHARPNESS_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_SHARPNESS_CONTROL 清晰度")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_SHARPNESS_CONTROL 清晰度")).valL}", 16);

                    }
                    if (IS_GAMMA.IsEnabled)
                    {
                        GAMMA_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAMMA_CONTROL 伽马")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAMMA_CONTROL 伽马")).valL}", 16);

                    }
                    if (IS_BALANCE.IsEnabled)
                    {
                        BALANCE_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_CONTROL 白平衡")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_CONTROL 白平衡")).valL}", 16);

                    }
                    if (IS_Backlight.IsEnabled)
                    {
                        Backlight_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_BACKLIGHT_COMPENSATION_CONTROL 背光补偿")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_BACKLIGHT_COMPENSATION_CONTROL 背光补偿")).valL}", 16);

                    }
                    if (IS_GAIN.IsEnabled)
                    {
                        GAIN_Slider.Value = Convert.ToInt32($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAIN_CONTROL 增益")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAIN_CONTROL 增益")).valL}", 16);

                    }

                    if (IS_ZOOM.IsEnabled)
                    {
                        ZOOM_Slider.Value = Convert.ToInt32(PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.def_val, 16);

                    }
                    if (IS_FOCUS.IsEnabled)
                    {
                        FOCUS_Slider.Value = Convert.ToInt64($"{PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_ABSOLUTE_CONTROL 焦点")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_ABSOLUTE_CONTROL 焦点")).valL}", 16);

                    }
                    if (IS_EXPOSURE.IsEnabled)
                    {
                        EXPOSURE_Slider.Value = Convert.ToInt64($"{PuctHelp.Parameters.First(c => c.Note.Contains("CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 曝光")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 曝光")).valL}", 16);

                    }
                    if (IS_Panorama.IsEnabled)
                    {
                        Panorama_Slider.Value = Convert.ToInt32(PuctHelp.Panorama.def_val, 16);

                    }
                    if (IS_Tilt.IsEnabled)
                    {
                        Tilt_Slider.Value = Convert.ToInt32(PuctHelp.Tilt.def_val, 16);

                    }
                    if (IS_Rolling.IsEnabled)//滚动
                    {
                        Rolling_Slider.Value = Convert.ToInt64($"{PuctHelp.Parameters.First(c => c.Note.Contains("CT_ROLL_ABSOLUTE_CONTROL 滚动绝对控制")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("CT_ROLL_ABSOLUTE_CONTROL 滚动绝对控制")).valL}", 16);

                    }
                    var power_line = Convert.ToInt64($"{PuctHelp.Parameters.First(c => c.Note.Contains("PU_POWER_LINE_FREQUENCY_CONTROL 电源线路")).valH}{ PuctHelp.Parameters.First(c => c.Note.Contains("PU_POWER_LINE_FREQUENCY_CONTROL 电源线路")).valL}", 16);
                    if (power_line == 1)
                    {
                        POWER_LINE_Combox.SelectedIndex = 0;
                    }
                    else if (power_line == 2)
                    {
                        POWER_LINE_Combox.SelectedIndex = 1;
                    }
                }
                else
                {
                    BRIGHTNESS_Txt.Text = Convert.ToInt32(PuctHelp.PU_BRIGHTNESS_CONTROL.def_val, 16).ToString();
                    CONTRAST_Txt.Text = Convert.ToInt32(PuctHelp.PU_CONTRAST_CONTROL.def_val, 16).ToString();
                    HUE_Txt.Text = Convert.ToInt32(PuctHelp.PU_HUE_CONTROL.def_val, 16).ToString();
                    SATURATION_Txt.Text = Convert.ToInt32(PuctHelp.PU_SATURATION_CONTROL.def_val, 16).ToString();
                    SHARPNESS_Txt.Text = Convert.ToInt32(PuctHelp.PU_SHARPNESS_CONTROL.def_val, 16).ToString();
                    GAMMA_Txt.Text = Convert.ToInt32(PuctHelp.PU_GAMMA_CONTROL.def_val, 16).ToString();
                    BALANCE_Txt.Text = Convert.ToInt32(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_val, 16).ToString();
                    Backlight_Slider.Value = Convert.ToInt32(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.def_val, 16);
                    GAIN_Txt.Text = Convert.ToInt32(PuctHelp.PU_GAIN_CONTROL.def_val, 16).ToString();
                    ZOOM_Txt.Text = Convert.ToInt32(PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.def_val, 16).ToString();
                    FOCUS_Txt.Text = Convert.ToInt32(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_val, 16).ToString();
                    EXPOSURE_Txt.Text = Convert.ToInt64(PuctHelp.CT_AE_MODE_CONTROL.def_val, 16).ToString();
                    Panorama_Txt.Text = Convert.ToInt32(PuctHelp.Panorama.def_val, 16).ToString();
                    Tilt_Txt.Text = Convert.ToInt32(PuctHelp.Tilt.def_val, 16).ToString();
                    //Rolling_Slider.Value = Convert.ToInt32(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.def_val, 16);
                    BRIGHTNESS_Slider.Value = Convert.ToInt32(PuctHelp.PU_BRIGHTNESS_CONTROL.def_val, 16);
                    CONTRAST_Slider.Value = Convert.ToInt32(PuctHelp.PU_CONTRAST_CONTROL.def_val, 16);
                    HUE_Slider.Value = Convert.ToInt32(PuctHelp.PU_HUE_CONTROL.def_val, 16);
                    SATURATION_Slider.Value = Convert.ToInt32(PuctHelp.PU_SATURATION_CONTROL.def_val, 16);
                    SHARPNESS_Slider.Value = Convert.ToInt32(PuctHelp.PU_SHARPNESS_CONTROL.def_val, 16);
                    GAMMA_Slider.Value = Convert.ToInt32(PuctHelp.PU_GAMMA_CONTROL.def_val, 16);
                    BALANCE_Slider.Value = Convert.ToInt32(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_val, 16);
                    Backlight_Slider.Value = Convert.ToInt32(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.def_val, 16);
                    GAIN_Slider.Value = Convert.ToInt32(PuctHelp.PU_GAIN_CONTROL.def_val, 16);
                    ZOOM_Slider.Value = Convert.ToInt32(PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.def_val, 16);
                    FOCUS_Slider.Value = Convert.ToInt32(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_val, 16);
                    EXPOSURE_Slider.Value = Convert.ToInt64(PuctHelp.CT_AE_MODE_CONTROL.def_val, 16);
                    Panorama_Slider.Value = Convert.ToInt32(PuctHelp.Panorama.def_val, 16);
                    Tilt_Slider.Value = Convert.ToInt32(PuctHelp.Tilt.def_val, 16);
                    //Rolling_Slider.Value = Convert.ToInt32(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.def_val, 16); 

                    //设置图像方向的值 
                    var imageflipp_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("18ab") && c.AddrVal == AddressValueEnum.Val);
                    IsImageFlipping.IsEnabled = (imageflipp_l != -1);
                    if (imageflipp_l != -1 && flippingMap.ContainsValue(BinList[imageflipp_l].original))
                    {

                        ImageFlipping.SelectedIndex = flippingMap.First(x => x.Value == BinList[imageflipp_l].original).Key;
                    }
                    //电力线频率
                    var power_line_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("6a58") && c.AddrVal == AddressValueEnum.Val);

                    IsPOWER_LINE.IsEnabled = (power_line_l != -1);
                    if (PuctHelp.PU_POWER_LINE_FREQUENCY_CONTROL.def_val.Contains("01"))
                    {
                        POWER_LINE_Combox.SelectedIndex = 0;
                    }
                    if (PuctHelp.PU_POWER_LINE_FREQUENCY_CONTROL.def_val.Contains("02"))
                    {
                        POWER_LINE_Combox.SelectedIndex = 1;
                    }

                }
                UpdateProgressBar(90);
                //设置视频格式
                if (PuctHelp.videoIHDNum == 0x1)
                {
                    if (PuctHelp.videoSFormatMjpegIndex == 0x1)
                    {
                        MJ_RBtn.IsChecked = true;
                    }
                    if (PuctHelp.videoSFormatYuvIndex == 0x1)
                    {
                        Yuv_RBtn.IsChecked = true;
                    }

                }
                if (PuctHelp.videoIHDNum == 0x2)
                {
                    if (PuctHelp.videoSFormatMjpegIndex == 0x1)
                    {
                        M_Default_Y_RBtn.IsChecked = true;
                    }
                    if (PuctHelp.videoSFormatYuvIndex == 0x1)
                    {
                        Y_Default_M_RBtn.IsChecked = true;
                    }
                }

                //设置UVC拍照模式

                if (PuctHelp.videoIHDStillCapture == 0x0)
                {
                    SameResolution_RBtn.IsChecked = true;
                }
                if (PuctHelp.videoIHDStillCapture == 0x2)
                {
                    DifferentResolutions_RBtn.IsChecked = true;
                }
                //设置音频开关
                var audio_switch_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("12bd") && c.AddrVal == AddressValueEnum.Val);
                audio_switch_en.IsEnabled = (audio_switch_l != -1) && FindConfigData() > 0;
                if (audio_switch_l != -1)
                {
                    if ($"{BinList[audio_switch_l + 1].original}{BinList[audio_switch_l].original}" == "01")
                    {
                        audio_switch_en.IsChecked = true;
                    }
                }
                //设置MJPG 分辨率
                if (PuctHelp.VideoMjpegFTypes.Count > 0)
                {
                    var list = PuctHelp.VideoMjpegFTypes.Where(v => (v.videoSMjpegFTypeWidth != 0 || v.videoSMjpegFTypeHeight != 0) && v.IsDelect == false).ToList();
                    var uniqueList = list.GroupBy(v => new { v.videoSMjpegFTypeWidth, v.videoSMjpegFTypeHeight })
                                         .Select(g => g.OrderBy(v => v.videoSMjpegFTypeIndex).First()).ToList();
                    mj_Combo.ItemsSource = uniqueList;
                    mj_Combo.SelectedIndex = PuctHelp.videoSFormatMjpegDefaultIndex - 1;
                    mj_ListBox.ItemsSource = uniqueList;
                    mj_ListBox.SelectedIndex = PuctHelp.videoSFormatMjpegDefaultIndex - 1;
                }
                //设置YUV 分辨率
                if (PuctHelp.VideoYuvFTypes.Count > 0)
                {
                    var list = PuctHelp.VideoYuvFTypes.Where(v => (v.videoSYuvFTypeWidth != 0 || v.videoSYuvFTypeHeight != 0) && v.IsDelect == false).ToList();
                    var uniqueList = list.GroupBy(v => new { v.videoSYuvFTypeWidth, v.videoSYuvFTypeHeight })
                                         .Select(g => g.OrderBy(v => v.videoSYuvFTypeIndex).First()).ToList();

                    yuv_Combo.ItemsSource = uniqueList;
                    yuv_Combo.SelectedIndex = PuctHelp.videoSFormatYuvDefaultIndex - 1;
                    yuv_ListBox.ItemsSource = uniqueList;
                    yuv_ListBox.SelectedIndex = PuctHelp.videoSFormatYuvDefaultIndex - 1;
                }



                SettingPUCT.GetTotalDescription(BinList);
            });
        }




     

        public static uint BinToLength = 0x200014c0;
        private bool isButtonClicked = false; // 添加一个标志位来表示按钮是否已被点击
        private async void LoadProgramBtn2_Click(object sender, RoutedEventArgs e)
        {
            if (isButtonClicked)
            {
                return; // 如果按钮已被点击，则直接返回，不执行后续代码
            }
            // 显示 Loading 框

            //ShowLoad(true);
            IsLoading = Visibility.Visible;
            PuctHelp.InitializePuctModels();
            await Task.Run(() =>
            {
                // 在UI线程上更新ProgressBar的值  
               
                    isButtonClicked = true;

                    if (!IsUsbOpen)
                    {
                        ShowErrorMessage("请选择在线设备列表！");
                        isButtonClicked = false;
                        //ShowLoad(false);
                        IsLoading = Visibility.Hidden;
                        return;
                    }
                    uint temp0 = (uint)ReadRegister(BinHelp.BinToLength);
                    uint temp1 = (uint)ReadRegister(BinHelp.BinToLength + 1);
                    uint temp2 = (uint)ReadRegister(BinHelp.BinToLength + 2);
                    uint temp3 = (uint)ReadRegister(BinHelp.BinToLength + 3);

                    var SavePath = string.Format("{0}\\Xchip_Output_{1}.bin", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddHHmms"));

                    var binLength = Convert.ToUInt32($"{temp3.ToString("X2")}{temp2.ToString("X2")}{temp1.ToString("X2")}{temp0.ToString("X2")}", 16);
                    if (binLength == 0xFFFFFFFF || binLength == 0x0)
                    {
                        ShowErrorMessage("bin文件长度读取失败！");
                        //ShowLoad(false);
                        IsLoading = Visibility.Hidden;
                        return;
                    }
                    if (IntPtr.Size == 8)
                    {
                        XChipUSB.UsbFlashQuickReadFile64(SavePath, 0x0, binLength);
                    }
                    else
                    {
                        XChipUSB.UsbFlashQuickReadFile86(SavePath, 0x0, binLength);
                    }
                    int maxRetries = 5; // 设置最大重试次数  
                    int retryCount = 0;
                    while (retryCount < maxRetries)
                    {
                        // 检查文件是否存在且内容不为空  
                        if (File.Exists(SavePath) && new FileInfo(SavePath).Length > 0)
                        {
                            Console.WriteLine("文件存在且不为空");
                            break; // 文件已正确写入，退出循环  
                        }
                        // 等待一段时间再重试  
                        // 等待一段时间再重试  
                        Task.Delay(2000).Wait();
                        retryCount++;
                    }



                    LoadProgram(SavePath);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    LoadTxt2.Text = SavePath;
                });
               
                    ShowSuccessMessage($"加载程序完成！");
               
            });
            //try
            //{
            // 将标志位设置为 true，表示按钮已被点击
           
            //}
            //catch (Exception ex)
            //{
            //    ShowErrorMessage(ex.Message.ToString());
            //}
            //finally
            //{
                // 将标志位设置为 false，表示按钮点击事件处理完成
                isButtonClicked = false;
            IsLoading = Visibility.Hidden;
            //LoadName.Visibility = Visibility.Collapsed;
            //}

        }
        private  long ReadRegister(ulong addr,bool isShow = true)
        {
            
            uint pVule = 0x0;
            bool isbool;
            if (IntPtr.Size == 8)
            {
                isbool = XChipUSB.UsbRegisterRead64((uint)addr, ref pVule, false);
            }
            else
            {
                isbool = XChipUSB.UsbRegisterRead86((uint)addr, ref pVule, false);
            }
            if (isShow)
            {
                ShowSuccessMessage($"R:0x{addr.ToString("X2")} 0x{pVule.ToString("X2")}", 250);
            }
           
            if (!isbool&& isShow)
            {
                ShowErrorMessage("R:读写失败");
            }
            return pVule;
        }
        private void InitializeControls(DependencyObject parent)
        {
            // 确保在 UI 线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                int childCount = VisualTreeHelper.GetChildrenCount(parent);
                for (int i = 0; i < childCount; i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                    if (child is TextBox textBox)
                    {
                        if (textBox.Name == "MJPGTxt" || textBox.Name == "YUVTxt")
                        {
                            continue; // 跳过特定的 TextBox
                        }
                        textBox.Text = ""; // 清空 TextBox
                    }
                    else if (child is Slider slider)
                    {
                        slider.Value = 0; // 重置 Slider
                    }
                    else if (child is CheckBox checkBox)
                    {
                        checkBox.IsChecked = false; // 取消选中 CheckBox
                    }

                    // 递归调用，继续查找子控件
                    InitializeControls(child);
                }
            });
        }

        private void InitMethod()
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                IS_BALANCE.IsEnabled = false;
                IS_Backlight.IsEnabled = false;
                IS_CONTRAST.IsEnabled = false;
                IS_BRIGHTNESS.IsEnabled = false;
                IS_EXPOSURE.IsEnabled = false;
                IS_FOCUS.IsEnabled = false;
                IS_GAIN.IsEnabled = false;
                IS_GAMMA.IsEnabled = false;
                IS_HUE.IsEnabled = false;
                IS_Panorama.IsEnabled = false;
                IS_Rolling.IsEnabled = false;
                IS_SATURATION.IsEnabled = false;
                IS_SHARPNESS.IsEnabled = false;
                IS_Tilt.IsEnabled = false;
                IS_ZOOM.IsEnabled = false;

                mj_Combo.ItemsSource = null;
                mj_Combo.SelectedIndex = -1;
                mj_ListBox.ItemsSource = null;
                mj_ListBox.SelectedIndex = -1;

                yuv_Combo.ItemsSource = null;
                yuv_Combo.SelectedIndex = -1;
                yuv_ListBox.ItemsSource = null;
                yuv_ListBox.SelectedIndex = -1;
            });
            
            InitializeControls(this);

        }



        // 递归遍历 VisualTree 查找指定类型的控件
        private IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj == null)
                yield break;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                var child = VisualTreeHelper.GetChild(depObj, i);

                if (child is T)
                    yield return (T)child;

                foreach (var childOfChild in FindVisualChildren<T>(child))
                    yield return childOfChild;
            }
        }
        // 检查参数值是否与给定的字符串相等
        bool IsParameterEqual(PuctModels parameter, string valueH, string valueL)
        {
            return parameter.valH == valueH && parameter.valL == valueL;
        }

        

        private void shebei_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取选中的USB设备
            USBDeviceModel selectedDevice = shebei.SelectedItem as USBDeviceModel;

            // 执行你希望在选中事件中处理的逻辑
            if (selectedDevice != null)
            {
                // 处理选中的设备
                USBDeviceModelSelection = new USBDeviceModel();
                USBDeviceModelSelection = selectedDevice;
                
                //MessageBox.Show($"选中的设备：{selectedDevice.DeviceName}");
            }
            if (shebei.SelectedIndex>=0)
            {   
                GetDeviceInfo(USBDeviceList[shebei.SelectedIndex].DeviceNum);
            }
          



        }



        private void GetDeviceInfo(int selectedIndex)
        {
            bool success;
            PatchInfo patchInfo;
            CameraInfo cameraInfo;
            var selectedDevice = _usbDeviceList.FirstOrDefault(c => c.DeviceNum == selectedIndex);
            if (selectedDevice != null)
            {
                DeviceVid.Text = selectedDevice.VID;
                DevicePid.Text = selectedDevice.PID;
                DeviceName.Text = selectedDevice.DeviceName;
                selectedDevice.IsOpen = true;
            }

            const int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            IntPtr pBuff = Marshal.AllocHGlobal(buffer.Length);
            Marshal.Copy(buffer, 0, pBuff, buffer.Length);

            uint buffSize = (uint)buffer.Length;

            if (IntPtr.Size == 8)
            {
                IsUsbOpen = XChipUSB.UsbSelectDevice64(selectedIndex);
                success = XChipUSB.UsbGetPatchInfo64(out patchInfo);
                if (success)
                {
                    DeviceVer.Text = patchInfo.patchInfo;
                }

                success = XChipUSB.UsbGetXChipCameraInfo64(out cameraInfo);
                if (success)
                {
                    DeviceiManufacture.Text = cameraInfo.ManufacturerInfo;
                    DeviceiSerialNumber.Text = cameraInfo.SerialNumber;
                }
                bool result = XChipUSB.UsbGetFirmwareVersionInfo64(pBuff, ref buffSize);
                if (result)
                {
                    // 复制结果回托管数组
                    byte[] resultBuffer = new byte[buffSize];
                    Marshal.Copy(pBuff, resultBuffer, 0, (int)buffSize);

                    // 将字节数组转换为字符串（假设固件版本信息是字符串）
                    string firmwareVersion = System.Text.Encoding.ASCII.GetString(resultBuffer).TrimEnd('\0');
                    DevicefwName.Text = firmwareVersion;
                    Console.WriteLine("Firmware Version: " + firmwareVersion);
                }

              
            }
            else
            {
                IsUsbOpen = XChipUSB.UsbSelectDevice86(selectedIndex);
                success = XChipUSB.UsbGetPatchInfo86(out patchInfo);
                if (success)
                {
                    DeviceVer.Text = patchInfo.patchInfo;
                }

                success = XChipUSB.UsbGetXChipCameraInfo86(out cameraInfo);
                if (success)
                {
                    DeviceiManufacture.Text = cameraInfo.ManufacturerInfo;
                    DeviceiSerialNumber.Text = cameraInfo.SerialNumber;
                }
                bool result = XChipUSB.UsbGetFirmwareVersionInfo86(pBuff, ref buffSize);
                if (result)
                {
                    // 复制结果回托管数组
                    byte[] resultBuffer = new byte[buffSize];
                    Marshal.Copy(pBuff, resultBuffer, 0, (int)buffSize);

                    // 将字节数组转换为字符串（假设固件版本信息是字符串）
                    string firmwareVersion = System.Text.Encoding.ASCII.GetString(resultBuffer).TrimEnd('\0');
                    DevicefwName.Text = firmwareVersion;
                    Console.WriteLine("Firmware Version: " + firmwareVersion);
                }
            }
        }

        private  void BRIGHTNESS_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_BRIGHTNESS.IsEnabled)
            {
                return;
            }
           
            if ( !PuctHelp.IsPuct && !PuctHelp.PU_BRIGHTNESS_CONTROL.def_bool)
            {
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 亮度(B) 相关配置！请检查！");
                return;
            }
                BRIGHTNESS_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
               
                int hexValue;

                if (!int.TryParse(BRIGHTNESS_Txt.Text, out hexValue))
                {
                    BRIGHTNESS_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_BRIGHTNESS_CONTROL 亮度")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_BRIGHTNESS_CONTROL 亮度")).valL = lowByte.ToString("X2");
                }
               
                PuctHelp.PU_BRIGHTNESS_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void CONTRAST_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_CONTRAST.IsEnabled) return;
           
            if (!PuctHelp.IsPuct && !PuctHelp.PU_CONTRAST_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 对比度(C) 相关配置！请检查！");
                return;
            }
            CONTRAST_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(CONTRAST_Txt.Text, out hexValue))
                {
                    CONTRAST_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_CONTRAST_CONTROL 对比度")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_CONTRAST_CONTROL 对比度")).valL = lowByte.ToString("X2");
                }
                    PuctHelp.PU_CONTRAST_CONTROL.cur_val = hexValue.ToString("X2");

            
        }

        private  void HUE_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_HUE.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_HUE_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 色调(H) 相关配置！请检查！");
                return;
            }
            HUE_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(HUE_Txt.Text, out hexValue))
                {
                    HUE_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_HUE_CONTROL 色调")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_HUE_CONTROL 色调")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_HUE_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void SATURATION_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_SATURATION.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_SATURATION_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 饱和度(S) 相关配置！请检查！");
                return;
            }
            SATURATION_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(SATURATION_Txt.Text, out hexValue))
                {
                    SATURATION_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_SATURATION_CONTROL 饱和度")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_SATURATION_CONTROL 饱和度")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_SATURATION_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void SHARPNESS_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_SHARPNESS.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_SHARPNESS_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 清晰度(P) 相关配置！请检查！");
                return;
            }
            SHARPNESS_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(SHARPNESS_Txt.Text, out hexValue))
                {
                    SHARPNESS_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_SHARPNESS_CONTROL 清晰度")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_SHARPNESS_CONTROL 清晰度")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_SHARPNESS_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void GAMMA_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_GAMMA.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_GAMMA_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 伽马(G) 相关配置！请检查！");
                return;
            }
            GAMMA_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(GAMMA_Txt.Text, out hexValue))
                {
                    GAMMA_Txt.Text = "1"; // 如果转换异常，将文本框的值设为0
                    hexValue = 1;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAMMA_CONTROL 伽马")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAMMA_CONTROL 伽马")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_GAMMA_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void BALANCE_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_BALANCE.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.def_bool)
            {
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 白平衡(W) 相关配置！请检查！");
                return;
            }
            BALANCE_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(BALANCE_Txt.Text, out hexValue))
                {
                    BALANCE_Txt.Text = "1"; // 如果转换异常，将文本框的值设为0
                    hexValue = 1;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_CONTROL 白平衡")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_CONTROL 白平衡")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.cur_val = hexValue.ToString("X2");
            

        }

        private  void Backlight_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_Backlight.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 逆光对比(B) 相关配置！请检查！");
                return;
            }
            Backlight_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(Backlight_Txt.Text, out hexValue))
                {
                    Backlight_Txt.Text = "-1"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_BACKLIGHT_COMPENSATION_CONTROL 背光补偿")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_BACKLIGHT_COMPENSATION_CONTROL 背光补偿")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        private  void GAIN_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_GAIN.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.PU_GAIN_CONTROL.def_bool)
            {
                
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 增益(G) 相关配置！请检查！");
                return;
            }
            GAIN_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(GAIN_Txt.Text, out hexValue))
                {
                    GAIN_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAIN_CONTROL 增益")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("PU_GAIN_CONTROL 增益")).valL = lowByte.ToString("X2");
                }
                PuctHelp.PU_GAIN_CONTROL.cur_val = hexValue.ToString("X2");
            
        }
        /// <summary>
        /// 缩放
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void ZOOM_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_ZOOM.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 缩放(Z) 相关配置！请检查！");
                return;
            }
            ZOOM_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(ZOOM_Txt.Text, out hexValue))
                {
                    ZOOM_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_ZOOM_ABSOLUTE_CONTROL 缩放")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_ZOOM_ABSOLUTE_CONTROL 缩放")).valL = lowByte.ToString("X2");
                }
                PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.cur_val = hexValue.ToString("X2");
            
        }
       /// <summary>
       /// 焦点
       /// </summary>
       /// <param name="sender"></param>
       /// <param name="e"></param>
        private  void FOCUS_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_FOCUS.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.def_bool)
            {
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 焦点(F) 相关配置！请检查！");
                return;
            }
            FOCUS_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(FOCUS_Txt.Text, out hexValue))
                {
                    FOCUS_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_ABSOLUTE_CONTROL 焦点")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_ABSOLUTE_CONTROL 焦点")).valL = lowByte.ToString("X2");
                }
                PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.cur_val = hexValue.ToString("X4");
            
        }
        /// <summary>
        /// 曝光
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void EXPOSURE_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_EXPOSURE.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.CT_AE_MODE_CONTROL.def_bool)
            {
               
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 曝光(E) 相关配置！请检查！");
                return;
            }
            EXPOSURE_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(EXPOSURE_Txt.Text, out hexValue))
                {
                    EXPOSURE_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int lowByte = hexValue & 0xFFFF; // 获取低位字节
                    var highByte = (hexValue >> 16) & 0xFFFF; // 获取高位字节
                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 曝光")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 曝光")).valL = lowByte.ToString("X2");
                }
                PuctHelp.CT_AE_MODE_CONTROL.cur_val = ((hexValue) & 0xFFFF).ToString("X2");
            
        }
        /// <summary>
        /// 全景
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void Panorama_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_Panorama.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.Panorama.def_bool)
            {
              
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 全景(P) 相关配置！请检查！");
                return;
            }
            Panorama_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(Panorama_Txt.Text, out hexValue))
                {
                    Panorama_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    //PuctHelp.Parameters.First(c => c.Note.Contains("CT_AE_MODE_CONTROL AE_MODE")).valH = highByte.ToString("X2");
                    //PuctHelp.Parameters.First(c => c.Note.Contains("CT_AE_MODE_CONTROL AE_MODE")).valL = lowByte.ToString("X2");
                }

                PuctHelp.Panorama.cur_val = hexValue.ToString("X2");
            
        }
        /// <summary>
        /// 倾斜
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void Tilt_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_Tilt.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.Tilt.def_bool)
            {
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 倾斜(T) 相关配置！请检查！");
                return;
            }
            Tilt_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(Tilt_Txt.Text, out hexValue))
                {
                    Tilt_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节
                }
                PuctHelp.Tilt.cur_val = hexValue.ToString("X2");
            
        }
        /// <summary>
        /// 滚动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void Rolling_Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (!IS_Rolling.IsEnabled) return;
            if (!PuctHelp.IsPuct && !PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.def_bool)
            {
                ShowErrorMessage("PUCT参数区或者Setting0_1区无 滚动(R) 相关配置！请检查！");
                return;
            }
            Rolling_Txt.Text = (Convert.ToInt32(e.NewValue)).ToString();
                int hexValue;

                if (!int.TryParse(Rolling_Txt.Text, out hexValue))
                {
                    Rolling_Txt.Text = "0"; // 如果转换异常，将文本框的值设为0
                    hexValue = 0;
                }
                if (PuctHelp.IsPuct)
                {
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_ROLL_ABSOLUTE_CONTROL 滚动")).valH = highByte.ToString("X2");
                    PuctHelp.Parameters.First(c => c.Note.Contains("CT_ROLL_ABSOLUTE_CONTROL 滚动")).valL = lowByte.ToString("X2");
                    //设置在puct 情况下  图像方向和滚动是一致的
                    ImageFlipping.SelectedIndex = lowByte;
                }
                PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.cur_val = hexValue.ToString("X2");
            
        }

        /// <summary>
        /// 设备名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserDevice_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
            if (isButtonClicked)
            {
                return; // 如果按钮已被点击，则直接返回，不执行后续代码
            }
            isButtonClicked = true;
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }
            //if (UserDevicCheck.IsChecked.GetValueOrDefault())
            //{
            //    // 判断input 最后一个字节是否是数字，是数字则加1，不是数字则添加0
            //    if (char.IsDigit(input[input.Length - 1]))
            //    {
            //        input += (char)((int)input[input.Length - 1] + 1);
            //    }
            //    else
            //    {
            //        input += '0';
            //    }
            //    textBox.Text = input;
            //}
            for (int i = 2; i < PuctHelp.userParametersUsb.VideoList.Count; i++)
            {
                PuctHelp.userParametersUsb.VideoList[i] = 0x0;
            }
            byte[] byteArray = ConvertToNewArray(Encoding.ASCII.GetBytes(input));
            if (byteArray.Count() > (PuctHelp.userParametersUsb.VideoList.Count()-2))
            {
                isButtonClicked = false;
                ShowErrorMessage("设备名称超过最大的限度！请调整长度！");
                return;
            }
            PuctHelp.userParametersUsb.VideoList[0] = (byte)(byteArray.Count() + 2);
            for (int i = 0; i < byteArray.Count(); i++)
            {
                PuctHelp.userParametersUsb.VideoList[2 + i] = byteArray[i];
            }
            isButtonClicked = false;
            ShowSuccessMessage("设备名称成功修改！");

        }
        /// <summary>
        /// Manufacture 名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserManufacture_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }
            for (int i = 2; i < PuctHelp.userParametersUsb.ManufactureList.Count; i++)
            {
                PuctHelp.userParametersUsb.ManufactureList[i] = 0x0;
            }
            byte[] byteArray = ConvertToNewArray(Encoding.ASCII.GetBytes(input));
            if (byteArray.Count() > (PuctHelp.userParametersUsb.ManufactureList.Count() - 2))
            {
                
                ShowErrorMessage("Manufacture 名称 超过最大的限度！请调整长度！");
                return;
            }
            PuctHelp.userParametersUsb.ManufactureList[0] = (byte)(byteArray.Count() + 2);
            for (int i = 0; i < byteArray.Count(); i++)
            {
                PuctHelp.userParametersUsb.ManufactureList[2 + i] = byteArray[i];
            }
        
            ShowSuccessMessage("Manufacture 名称 成功修改！");
        }
        /// <summary>
        /// SerialNumber
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserSerialNumber_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
           
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }
            for (int i = 2; i < PuctHelp.userParametersUsb.SerialNumberList.Count; i++)
            {
                PuctHelp.userParametersUsb.SerialNumberList[i] = 0x0;
            }
            byte[] byteArray = ConvertToNewArray(Encoding.ASCII.GetBytes(input));
            if (byteArray.Count() > (PuctHelp.userParametersUsb.SerialNumberList.Count() - 2))
            {
                ShowErrorMessage("SerialNumber 名称 超过最大的限度！请调整长度！");
                return;
            }
            PuctHelp.userParametersUsb.SerialNumberList[0] = (byte)(byteArray.Count()+2);
            for (int i = 0; i < byteArray.Count(); i++)
            {
                PuctHelp.userParametersUsb.SerialNumberList[2 + i] = byteArray[i];
            }
            
            ShowSuccessMessage("SerialNumber 名称 成功修改！");
        }
        /// <summary>
        /// Vid 名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserVid_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input)||input.Length<4)
            {
                return;
            }
            // 验证输入是否为4位的十六进制数
            bool isValid = Regex.IsMatch(input, "^[0-9A-Fa-f]{4}$");

            if (!isValid)
            {
                ShowErrorMessage("请输入4位的VID名称十六进制数！");
                return;
            }
            //处理逻辑
            var decNumber = Convert.ToInt32(input, 16);
            var highByte = (byte)((decNumber >> 8) & 0xFF);
            var lowByte = (byte)(decNumber & 0xFF);

            //PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 1))].original =
            PuctHelp.userParametersUsb.VidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))].original = lowByte;
            //PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 1))].original =
            PuctHelp.userParametersUsb.VidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))].original = highByte;

            
            ShowSuccessMessage("成功修改4位的VID名称！");
        }
        /// <summary>
        /// pid 名称
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserPid_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input) || input.Length < 4)
            {
                return;
            }
            // 验证输入是否为4位的十六进制数
            bool isValid = Regex.IsMatch(input, "^[0-9A-Fa-f]{4}$");

            if (!isValid)
            {
                ShowErrorMessage("请输入4位的PID名称十六进制数！");
                return;
            }

            //处理逻辑
            //处理逻辑
            var decNumber = Convert.ToInt32(input, 16);
            var highByte = (byte)((decNumber >> 8) & 0xFF);
            var lowByte = (byte)(decNumber & 0xFF);

            //PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 1))].original =
            PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))].original = lowByte;
            //PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 1))].original =
            PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))].original = highByte;

          
            ShowSuccessMessage("成功修改4位的PID名称！");
        }
        /// <summary>
        /// 设备名称（音频）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void UserMic_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if ((bool)!isEn.IsChecked) return;
            TextBox textBox = (TextBox)sender;
            string input = textBox.Text.Trim();
            if (string.IsNullOrWhiteSpace(input))
            {
                return;
            }
            for (int i = 2; i < PuctHelp.userParametersUsb.VideoMicList.Count; i++)
            {
                PuctHelp.userParametersUsb.VideoMicList[i] = 0x0;
            }
            byte[] byteArray = ConvertToNewArray( Encoding.ASCII.GetBytes(input));
            if (byteArray.Count() > (PuctHelp.userParametersUsb.VideoMicList.Count() - 2))
            {
                
                ShowErrorMessage("设备名称（音频） 超过最大的限度！请调整长度！");
                return;
            }
            PuctHelp.userParametersUsb.VideoMicList[0] = (byte)(byteArray.Count() + 2);
            for (int i = 0; i < byteArray.Count(); i++)
            {
                PuctHelp.userParametersUsb.VideoMicList[2 + i] = byteArray[i];
            }
           

            ShowSuccessMessage("设备名称（音频） 成功修改！");
        }


        public  byte[] ConvertToNewArray(byte[] byteArray)
        {
            byte[] newArray = new byte[byteArray.Length * 2];

            for (int i = 0; i < byteArray.Length; i++)
            {
                newArray[i * 2] = byteArray[i];
                newArray[i * 2 + 1] = 0x0;
            }

            return newArray;
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void downloadBtn_Click(object sender, RoutedEventArgs e)
        {
            if (BinList == null || BinList.Count <= 0)
            {
                ShowErrorMessage("请先加载有效Bin文件！");
                return;
            }
            if (isButtonClicked)
            {
                return; // 如果按钮已被点击，则直接返回，不执行后续代码
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Bin files (*.bin)|*.bin";
            if (saveFileDialog.ShowDialog() != true) return;
            //ShowLoad(true);
            // 立即显示加载指示器
            IsLoading = Visibility.Visible;

            // 执行异步操作（例如保存数据）
            await Task.Run(() =>
            {
                
                    int bytesPerLine = 2;
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    if (IsMsgPrint) //是否打印
                    {
                        StringBuilder originalOutput = new StringBuilder();

                        for (int i = 0; i < PuctHelp.ConfigurationDescriptorResult.Count; i += bytesPerLine)
                        {
                            StringBuilder line = new StringBuilder();

                            for (int j = i; j < i + bytesPerLine && j < PuctHelp.ConfigurationDescriptorResult.Count; j++)
                            {
                                line.Append($"{PuctHelp.ConfigurationDescriptorResult[j].original.ToString("X2")} ");
                            }

                            originalOutput.AppendLine(line.ToString());
                        }


                        string originalFilePath = System.IO.Path.Combine(desktopPath, "original.txt");

                        File.WriteAllText(originalFilePath, originalOutput.ToString());

                    }


                    UpdateProgressBar(0);
                    isButtonClicked = true;
                    AutoWhiteBalanceIsCheck();
                    UpdateProgressBar(10);
                    AutoFocusIsCheck();
                    UpdateProgressBar(20);
                    AutoExposureIsCheck();
                    //更新 Bin中Pid\Vid
                    foreach (var item in BinList)
                    {
                        if (PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))].original;
                        }
                        if (PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))].original;
                        }

                        if (PuctHelp.userParametersUsb.VidAddrL[PuctHelp.userParametersUsb.VidAddrL.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.VidAddrL[PuctHelp.userParametersUsb.VidAddrL.FindIndex((c => c.sort == 0))].original;
                        }
                        if (PuctHelp.userParametersUsb.VidAddrH[PuctHelp.userParametersUsb.VidAddrH.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.VidAddrH[PuctHelp.userParametersUsb.VidAddrH.FindIndex((c => c.sort == 0))].original;
                        }
                    }
                    UpdateProgressBar(30);
                    //更新 Bin中设备名称
                    //更新 Bin中Manufacture
                    //更新 Bin中SerialNumber
                    //更新 Bin中 设备名称（音频）
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.VideoMicStartIndex, PuctHelp.userParametersUsb.VideoMicEndIndex, PuctHelp.userParametersUsb.VideoMicList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.VideoStartIndex, PuctHelp.userParametersUsb.VideoEndIndex, PuctHelp.userParametersUsb.VideoList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.ManufactureStartIndex, PuctHelp.userParametersUsb.ManufactureEndIndex, PuctHelp.userParametersUsb.ManufactureList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.SerialNumberStartIndex, PuctHelp.userParametersUsb.SerialNumberEndIndex, PuctHelp.userParametersUsb.SerialNumberList);
                    UpdateProgressBar(40);
                    ///参数配置  分为两种模式 一种存在puct  一种不存在puct
                    if (PuctHelp.IsPuct)
                    {
                        UpdateBinListWithParameters(PuctHelp.PuctIndex);
                    }

                    if (PuctHelp.AppSetting0_0Count > 0 && PuctHelp.AppSetting0_0StartData > 0)
                    {
                        UpdateBinListWithControlValue(PuctHelp.PU_BRIGHTNESS_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_CONTRAST_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_HUE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_SATURATION_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_SHARPNESS_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_GAMMA_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_GAIN_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_AE_MODE_CONTROL, "曝光");
                        UpdateBinListWithControlValue(PuctHelp.PU_POWER_LINE_FREQUENCY_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL);

                        UpdateBinListWithControlValue(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_FOCUS_AUTO_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_AE_MODE_AUTO_CONTROL);
                    }
                    UpdateProgressBar(50);

                    //更新UVC拍照
                    UpdateBinListWithVideoIHDResult(PuctHelp.VideoIHDResult, PuctHelp.videoIHDStillCapture);




                    //PuctHelp.StillImageFrameTypeResultOne 处理截图信息 修改bLength长度 修改bNumImageSizePatterns数量 删除width x wHeight

                    //PuctHelp.StillImageFrameTypeResultTwo 处理截图信息 修改bLength长度 修改bNumImageSizePatterns数量 删除width x wHeight


                    //更新Mj默认分辨率
                    //UpdateBinListWithVideoSFormatResult(PuctHelp.VideoSFormatMjpegResult, PuctHelp.videoSFormatMjpegDefaultIndex);
                    ////更新YUV默认分辨率
                    //UpdateBinListWithVideoSFormatResult(PuctHelp.VideoSFormatYuvResult, PuctHelp.videoSFormatYuvDefaultIndex);

                    //重新获取描述符总个数
                    SettingPUCT.GetTotalDescription(BinList);


                    //更新mj的描述符  PuctHelp.VideoMjpegFTypes
                    //更新yuv的描述符 PuctHelp.VideoYuvFTypes
                    //PuctHelp.ConfigurationDescriptorResult 先输出 字段original 每次输出8个字节一行 测试文本  在输出  每次输出8个字节一行字段original修改后的文本


                    //重新更新PuctHelp.ConfigurationDescriptorResult

                    ProcessVideoFTypeData();

                    if (IsMsgPrint)
                    {
                        StringBuilder LastOutput = new StringBuilder();
                        for (int i = 0; i < PuctHelp.ConfigurationDescriptorResult.Count; i += bytesPerLine)
                        {
                            StringBuilder line = new StringBuilder();

                            for (int j = i; j < i + bytesPerLine && j < PuctHelp.ConfigurationDescriptorResult.Count; j++)
                            {
                                line.Append($"{PuctHelp.ConfigurationDescriptorResult[j].original.ToString("X2")} ");
                            }

                            LastOutput.AppendLine(line.ToString());
                        }

                        string lastFilePath = System.IO.Path.Combine(desktopPath, "last.txt");
                        File.WriteAllText(lastFilePath, LastOutput.ToString());
                    }
                    UpdateProgressBar(60);

                    //crc校验
                    UpdateBinListWithCrcCheck();
                    UpdateProgressBar(70);

                    BinHelp.BinOutFile(saveFileDialog.FileName, BinList);
                    //HandyControl.Controls.Growl.Success(new GrowlInfo()
                    //{
                    //    Message = $"下载成功， 路径地址：{saveFileDialog.FileName}",
                    //    Token = "SuccessMsg",
                    //    ShowCloseButton = true,
                    //    ShowDateTime = true
                    //});
                    //await Task.Delay(3000);
                    //HandyControl.Controls.Growl.Clear("SuccessMsg");
                    UpdateProgressBar(90);
                    isButtonClicked = false;
                //LoadProgram(LoadTxt1.Text);
                Application.Current.Dispatcher.Invoke(() =>
                {
                    LoadTxt1.Text = "";
                });
                BinList = null;
                UpdateProgressBar(100);
                ShowSuccessMessage($"下载成功，路径地址：{saveFileDialog.FileName}");
                    
                    //ShowLoad(false);
                    _ = Task.Delay(3000).ContinueWith(_ =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            UpdateProgressBar(0);
                        });
                    });
               
            });

            // 异步操作完成后隐藏加载指示器
            IsLoading = Visibility.Hidden;

            
        }


        /// <summary>
        /// 更新BinList中的Pid/Vid
        /// </summary>
        /// <param name="pidVidList"></param>
        /// <param name="sort"></param>
        private void UpdateBinListWithPidVid(List<BinBase> pidVidList, int sort)
        {
            var index = pidVidList.FindIndex(c => c.sort == sort);
            if (index != -1)
            {
                BinList[index].original = pidVidList[index].original;
            }
        }
        /// <summary>
        /// 更新BinList中的设备名称
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <param name="dataList"></param>
        private void UpdateBinListWithDeviceName(int startIndex, int endIndex, List<byte> dataList)
        {
            int index = 0;
            for (int i = startIndex - 3; i < endIndex + 3; i++)
            {
                if (BinList[i].smallexample.Contains("FFF8") || BinList[i].smallexample.Contains("FFF9") || BinList[i].smallexample.Contains("F6F5")) continue;
                BinList[i].original = dataList[index + 3];
                BinList[i + 1].original = dataList[index + 2];
                BinList[i + 2].original = dataList[index + 1];
                BinList[i + 3].original = dataList[index];
                i += 3;
                index += 4;
            }
        }
        /// <summary>
        /// 更新BinList中的参数
        /// </summary>
        /// <param name="puctIndex"></param>
        private void UpdateBinListWithParameters(int puctIndex)
        {
            for (int i = 0; i < PuctHelp.Parameters.Count(); i++)
            {
                if (PuctHelp.Parameters[i].Note.Contains("CT_EXPOSURE_TIME_ABSOLUTE_CONTROL 曝光"))
                {
                    var tempUint = SettingPUCT.GetPuct_EXPOSURE($"{PuctHelp.Parameters[i].valL}");
                    BinList[(i * 2) + puctIndex].original = (byte)(tempUint & 0xff);
                    BinList[(i * 2) + puctIndex + 1].original = (byte)(tempUint >> 8 & 0xff);
                }
                else
                {
                    BinList[(i * 2) + puctIndex].original = Convert.ToByte(PuctHelp.Parameters[i].valL, 16);
                    BinList[(i * 2) + puctIndex + 1].original = Convert.ToByte(PuctHelp.Parameters[i].valH, 16);
                }
            }
        }
        /// <summary>
        /// 更新BinList中的控制值
        /// </summary>
        /// <param name="controlValue"></param>
        /// <param name="temp"></param>
        private void UpdateBinListWithControlValue(PuctModel controlValue, string temp = "")
        {
            if (!string.IsNullOrWhiteSpace(controlValue.def_addr_h))
            {
                var indexH = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count,
                    c => c.addrsmallex.ToLower().Contains(controlValue.def_addr_h.ToLower()) && c.AddrVal == AddressValueEnum.Val);
                if (indexH != -1)
                {
                    var tempUint = GetTempUint(controlValue.cur_val, temp);

                    BinList[indexH].original = (byte)(tempUint >> 8 & 0xff);
                    BinList[indexH + 1].original = 0x00;
                }
            }

            if (!string.IsNullOrWhiteSpace(controlValue.def_addr_l))
            {
                var indexL = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count,
                    c => c.addrsmallex.ToLower().Contains(controlValue.def_addr_l.ToLower()) && c.AddrVal == AddressValueEnum.Val);
                if (indexL != -1)
                {
                    var tempUint = GetTempUint(controlValue.cur_val, temp);

                    BinList[indexL].original = (byte)(tempUint & 0xff);
                    BinList[indexL + 1].original = 0x00;
                }
            }
        }
        /// <summary>
        /// 获取临时的UInt32值
        /// </summary>
        /// <param name="cur_val"></param>
        /// <param name="temp"></param>
        /// <returns></returns>
        private uint GetTempUint(string cur_val, string temp)
        {
            uint tempUint;

            if (temp.Contains("曝光"))
            {
                tempUint = (uint)SettingPUCT.GetPuct_EXPOSURE(cur_val);
            }
            else
            {
                tempUint = Convert.ToUInt32(cur_val, 16);
            }

            return tempUint;
        }
        /// <summary>
        /// 更新BinList中的视频IHD结果
        /// </summary>
        /// <param name="videoIHDResult"></param>
        /// <param name="videoIHDStillCapture"></param>
        private void UpdateBinListWithVideoIHDResult(List<BinBase> videoIHDResult, int videoIHDStillCapture)
        {
            if (videoIHDResult.Count == 0x0F)
            {
                videoIHDResult[9].original = (byte)videoIHDStillCapture;
                foreach (var item in videoIHDResult)
                {
                    BinList.Find(c => c.addrsmallex == item.addrsmallex && c.module == item.module && c.note == item.note && c.sort == item.sort).original = item.original;
                }
            }
        }
        /// <summary>
        /// 更新BinList中的视频SFormat结果
        /// </summary>
        /// <param name="videoSFormatResult"></param>
        /// <param name="defaultIndex"></param>
        private void UpdateBinListWithVideoSFormatResult(List<BinBase> videoSFormatResult, int defaultIndex)
        {
            if (videoSFormatResult.Count == 0x0B || videoSFormatResult.Count == 0x1B)
            {
                videoSFormatResult[videoSFormatResult.Count - 5].original = (byte)defaultIndex;
                foreach (var item in videoSFormatResult)
                {
                    BinList.Find(c => c.addrsmallex == item.addrsmallex && c.module == item.module && c.note == item.note && c.sort == item.sort).original = item.original;
                }
            }
        }
        /// <summary>
        /// 更新BinList中的CRC校验
        /// </summary>
        private void UpdateBinListWithCrcCheck()
        {
            StringBuilder crcSb = new StringBuilder();
            for (int i = 0; i < BinList.Count; i++)
            {
                if (BinList[i].smalladdr.ToLower() == "f6f5" && BinList[i].IsSetting == true)
                {
                    var CrcIndex = i;

                    Byte[] crcList = new Byte[256];
                    for (int j = 0; j < crcList.Count(); j++)
                    {
                        crcList[j] = BinList[CrcIndex + j + 1].original;
                    }

                    var crcData = BinHelp.XchipCrcCheck16(0xFFFF, crcList);

                    if (BinList[CrcIndex].original == 0xf6 && BinList[CrcIndex - 1].original == 0xf5)
                    {
                        crcSb.Append($"CRC更新索引：{CrcIndex}   原始值：{ BinList[CrcIndex - 3].original.ToString("X")}{ BinList[CrcIndex - 2].original.ToString("X") }  更新值 ：{crcData.ToString("X")}\r\n");
                        BinList[CrcIndex - 3].original = (byte)(crcData & 0xff);
                        BinList[CrcIndex - 2].original = (byte)(crcData >> 8 & 0xff);
                    }
                }
            }
        }



        private void UpdateBinListWithControlValue(string defAddrH, string defAddrL,string cur_val,string temp = "")
        {
            // 添加等于空的时候不操作寄存器
            if (!string.IsNullOrWhiteSpace(defAddrH))
            {
                var indexH = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count,
                c => c.addrsmallex.ToLower().Contains(defAddrH.ToLower()) && c.AddrVal == AddressValueEnum.Val);
                if (indexH != -1)
                {
                    if (temp.Contains("曝光"))
                    {
                        var tempUint = SettingPUCT.GetPuct_EXPOSURE(cur_val);

                        BinList[indexH].original = (byte)(tempUint >> 8 & 0xff);
                        BinList[indexH + 1].original = (byte)(00);
                    }
                    else
                    {
                        var tempUint = Convert.ToUInt32(cur_val, 16);
                        BinList[indexH].original = (byte)(tempUint >> 8 & 0xff);
                        BinList[indexH + 1].original = (byte)(0x0);
                    }

                }
            }
            // 添加等于空的时候不操作寄存器
            if (!string.IsNullOrWhiteSpace(defAddrL))
            {
                var indexL = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count,
                c => c.addrsmallex.ToLower().Contains(defAddrL.ToLower()) && c.AddrVal == AddressValueEnum.Val);
                if (indexL != -1)
                {
                    if (temp.Contains("曝光"))
                    {
                        var tempUint = SettingPUCT.GetPuct_EXPOSURE(cur_val);

                        BinList[indexL].original = (byte)(tempUint & 0xff);
                        BinList[indexL + 1].original = (byte)(00);
                    }
                    else
                    {
                        var tempUint = Convert.ToUInt32(cur_val, 16);
                        BinList[indexL].original = (byte)(tempUint & 0xff);
                        BinList[indexL + 1].original = (byte)(0x0);
                    }

                }
            }
            
        }



        private void BRIGHTNESS_Txt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            // 使用正则表达式验证输入是否为整数
            Regex regex = new Regex("[^0-9]+");
            if (!regex.IsMatch(e.Text))
            {
                var textB = sender as TextBox;
                textB.Text = Convert.ToInt32(textB.Text).ToString();
            } 
            e.Handled = regex.IsMatch(e.Text);
        }

        private void POWER_LINE_Combox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
           
            var selectedFrequency = POWER_LINE_Combox.SelectedItem as string;
            var hexValue = 0x0;
            if (selectedFrequency == "50Hz")
            {
                // 执行 50Hz 的操作
                hexValue = 0x1;
            }
            else if (selectedFrequency == "60Hz")
            {
                // 执行 60Hz 的操作
                hexValue = 0x2;
            }
           
            if (hexValue == 0x0) return;
            if (PuctHelp.IsPuct)
            {
                int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                int lowByte = hexValue & 0xFF; // 获取低位字节
                PuctHelp.Parameters.First(c => c.Note.Contains("PU_POWER_LINE_FREQUENCY_CONTROL 电源线路频")).valH = highByte.ToString("X2");
                PuctHelp.Parameters.First(c => c.Note.Contains("PU_POWER_LINE_FREQUENCY_CONTROL 电源线路频")).valL = lowByte.ToString("X2");
            }

            PuctHelp.PU_POWER_LINE_FREQUENCY_CONTROL.cur_val = hexValue.ToString("X");
        }

        private void AutoWhiteBalance_Checked(object sender, RoutedEventArgs e)
        {
            AutoWhiteBalanceIsCheck();

        }

        private void AutoWhiteBalanceIsCheck()
        {
            // 使用 Dispatcher.Invoke 确保在 UI 线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {     // 获取 AutoWhiteBalance 的检查状态
                var hexValue = (bool)AutoWhiteBalance.IsChecked ? 0x1 : 0x0;
                if (PuctHelp.IsPuct)
                {
                    // 获取高位和低位字节
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    // 更新参数
                    var parameter = PuctHelp.Parameters.First(c => c.Note.Contains("PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL 白平衡"));
                    parameter.valH = highByte.ToString("X2");
                    parameter.valL = lowByte.ToString("X2");
                }

                // 更新当前值
                PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL.cur_val = hexValue.ToString("X2");
            });
        }

        private void AutoFocus_Checked(object sender, RoutedEventArgs e)
        {
            //CT_FOCUS_AUTO_CONTROL 焦点自动控制
            AutoFocusIsCheck();

        }

        private void AutoFocusIsCheck()
        {
            

            // 使用 Dispatcher.Invoke 确保在 UI 线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {    // 获取 AutoFocus 的检查状态
                var hexValue = (bool)AutoFocus.IsChecked ? 0x1 : 0x0;
                if (PuctHelp.IsPuct)
                {
                    // 获取高位和低位字节
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    // 更新参数
                    var parameter = PuctHelp.Parameters.First(c => c.Note.Contains("CT_FOCUS_AUTO_CONTROL 焦点自动控制"));
                    parameter.valH = highByte.ToString("X2");
                    parameter.valL = lowByte.ToString("X2");
                }

                // 更新当前值
                PuctHelp.CT_FOCUS_AUTO_CONTROL.cur_val = hexValue.ToString("X2");
            });
        }


        private void AutoExposure_Checked(object sender, RoutedEventArgs e)
        {
            //CT_AE_MODE_CONTROL AE_MODE控制
            AutoExposureIsCheck();

        }

        private void AutoExposureIsCheck()
        {
            

            // 使用 Dispatcher.Invoke 确保在 UI 线程上执行
            Application.Current.Dispatcher.Invoke(() =>
            {
                // 获取 AutoExposure 的检查状态
                var hexValue = (bool)AutoExposure.IsChecked ? 0x2 : 0x1;
                if (PuctHelp.IsPuct)
                {
                    // 获取高位和低位字节
                    int highByte = (hexValue >> 8) & 0xFF; // 获取高位字节
                    int lowByte = hexValue & 0xFF; // 获取低位字节

                    // 更新参数
                    var parameter = PuctHelp.Parameters.First(c => c.Note.Contains("CT_AE_MODE_CONTROL AE_MODE控制"));
                    parameter.valH = highByte.ToString("X2");
                    parameter.valL = lowByte.ToString("X2");
                }

                // 更新当前值
                PuctHelp.CT_AE_MODE_AUTO_CONTROL.cur_val = hexValue.ToString("X2");
            });
        }



        /// <summary>
        /// UVC 拍照模式选中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SameResolution_RBtn_Checked(object sender, RoutedEventArgs e)
        {
           
            // 检查选中状态
            if (SameResolution_RBtn.IsChecked == true)
            {
                PuctHelp.videoIHDStillCapture = 0x0;

            }
            else if (DifferentResolutions_RBtn.IsChecked == true)
            {
                // 执行不同分辨率逻辑
                PuctHelp.videoIHDStillCapture = 0x2;
            }
           


        }

        //根据mj或者yuv生成描述
        public List<byte> GetMjpegImageDescriptor(List<VideoMjpegFType> vMjpegFTypes) {
            byte bLength = 0x1;
            List<byte> mjList = new List<byte>();
            mjList.Add(bLength);
            mjList.Add(0x24);
            mjList.Add(0x3);
            mjList.Add(0x0);
            mjList.Add((byte)vMjpegFTypes.Count());
            bLength += 4;
            HashSet<int> hashSet = new HashSet<int>();
            for (int i = 0; i < vMjpegFTypes.Count; i++)
            {
                int hash = vMjpegFTypes[i].videoSMjpegFTypeWidth.GetHashCode() ^ vMjpegFTypes[i].videoSMjpegFTypeHeight.GetHashCode();
                if (!hashSet.Contains(hash))
                {
                    mjList.Add((byte)(vMjpegFTypes[i].videoSMjpegFTypeWidth << 8 & 0xff));
                    mjList.Add((byte)(vMjpegFTypes[i].videoSMjpegFTypeWidth & 0xff));
                    mjList.Add((byte)(vMjpegFTypes[i].videoSMjpegFTypeHeight << 8 & 0xff));
                    mjList.Add((byte)(vMjpegFTypes[i].videoSMjpegFTypeHeight & 0xff));
                    bLength += 4;
                    hashSet.Add(hash);
                }
            }
            mjList.Add(0x0);
            bLength += 1;
            mjList[0] = bLength;

            //for (int i = 0; i < mjList.Count; i += 4)
            //{
            //    byte temp = mjList[i];
            //    mjList[i] = mjList[i + 3];
            //    mjList[i + 3] = temp;

            //    temp = mjList[i + 1];
            //    mjList[i + 1] = mjList[i + 2];
            //    mjList[i + 2] = temp;
            //}

            return mjList;

        }
        public List<byte> GetYuvImageDescriptor(List<VideoYuvFType> vYuvFType)
        {
            byte bLength = 0x1;
            List<byte> yuvList = new List<byte>();
            yuvList.Add(bLength);
            yuvList.Add(0x24);
            yuvList.Add(0x3);
            yuvList.Add(0x0);
            yuvList.Add((byte)vYuvFType.Count());
            bLength += 4;
            HashSet<int> hashSet = new HashSet<int>();
            for (int i = 0; i < vYuvFType.Count; i++)
            {
                int hash = vYuvFType[i].videoSYuvFTypeWidth.GetHashCode() ^ vYuvFType[i].videoSYuvFTypeHeight.GetHashCode();
                if (!hashSet.Contains(hash))
                {
                    yuvList.Add((byte)(vYuvFType[i].videoSYuvFTypeWidth << 8 & 0xff));
                    yuvList.Add((byte)(vYuvFType[i].videoSYuvFTypeWidth & 0xff));
                    yuvList.Add((byte)(vYuvFType[i].videoSYuvFTypeHeight << 8 & 0xff));
                    yuvList.Add((byte)(vYuvFType[i].videoSYuvFTypeHeight & 0xff));
                    bLength += 4;
                    hashSet.Add(hash);
                }
            }
            yuvList.Add(0x0);
            bLength += 1;
            yuvList[0] = bLength;

            //for (int i = 0; i < yuvList.Count; i += 4)
            //{
            //    byte temp = yuvList[i];
            //    yuvList[i] = yuvList[i + 3];
            //    yuvList[i + 3] = temp;

            //    temp = yuvList[i + 1];
            //    yuvList[i + 1] = yuvList[i + 2];
            //    yuvList[i + 2] = temp;
            //}
            return yuvList;
        }



        /// <summary>
        /// mjpg  默认分辨率
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mj_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsLoad) return;
           
            PuctHelp.videoSFormatMjpegDefaultIndex = mj_Combo.SelectedIndex + 1;
            mj_ListBox.SelectedIndex = mj_Combo.SelectedIndex;

        }
        /// <summary>
        /// yuv 默认分辨率
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void yuv_Combo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (IsLoad) return;
            PuctHelp.videoSFormatYuvDefaultIndex = yuv_Combo.SelectedIndex + 1;
            yuv_ListBox.SelectedIndex = yuv_Combo.SelectedIndex;
        }

        //private void yuv_ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    e.Handled = true;
        //}

        //private void mj_ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        //{
        //    e.Handled = true;
        //}

        private void Rolling_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(Rolling_Txt.Text, out int intValue))
            {
                
                Rolling_Slider.Value = intValue;
                PuctHelp.CT_ROLL_ABSOLUTE_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void Tilt_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(Tilt_Txt.Text, out int intValue))
            {
               
                Tilt_Slider.Value = intValue;
                PuctHelp.Tilt.cur_val = intValue.ToString("X2");
            }
        }

        private void Panorama_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(Panorama_Txt.Text, out int intValue))
            {
              
                Panorama_Slider.Value = intValue;
                PuctHelp.Panorama.cur_val = intValue.ToString("X2");
            }
        }

        private void EXPOSURE_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(EXPOSURE_Txt.Text, out int intValue))
            {
               
                EXPOSURE_Slider.Value = intValue;
                PuctHelp.CT_AE_MODE_CONTROL.cur_val = ((intValue) & 0xFFFF).ToString("X2");
            }
        }

        private void FOCUS_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(FOCUS_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                FOCUS_Slider.Value = intValue;
                PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL.cur_val = intValue.ToString("X4");
            }
        }

        private void ZOOM_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(ZOOM_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                ZOOM_Slider.Value = intValue;
                PuctHelp.CT_ZOOM_ABSOLUTE_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void GAIN_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(GAIN_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                GAIN_Slider.Value = intValue;
                PuctHelp.PU_GAIN_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void Backlight_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(Backlight_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                Backlight_Slider.Value = intValue;
                PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void BALANCE_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(BALANCE_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                BALANCE_Slider.Value = intValue;
                PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void GAMMA_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(GAMMA_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                GAMMA_Slider.Value = intValue;
                PuctHelp.PU_GAMMA_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void SHARPNESS_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(SHARPNESS_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                SHARPNESS_Slider.Value = intValue;
                PuctHelp.PU_SHARPNESS_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void SATURATION_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(SATURATION_Txt.Text, out int intValue))
            {
                // 更新 FOCUS_Slider 的值
                SATURATION_Slider.Value = intValue;
                PuctHelp.PU_SATURATION_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void HUE_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(HUE_Txt.Text, out int intValue))
            {
                
                HUE_Slider.Value = intValue;
                PuctHelp.PU_HUE_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void CONTRAST_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(CONTRAST_Txt.Text, out int intValue))
            {

                CONTRAST_Slider.Value = intValue;
                PuctHelp.PU_CONTRAST_CONTROL.cur_val = intValue.ToString("X2");
            }
        }

        private void BRIGHTNESS_Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            // 将文本框的值转换为整数
            if (int.TryParse(BRIGHTNESS_Txt.Text, out int intValue))
            {

                BRIGHTNESS_Slider.Value = intValue;
                PuctHelp.PU_BRIGHTNESS_CONTROL.cur_val = intValue.ToString("X2");
            }
        }
        /// <summary>
        /// 音频开关的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void audio_switch_en_Checked(object sender, RoutedEventArgs e)
        {
            if (BinList == null) return;
            
            // 执行打开音频逻辑
            var audio_switch_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("12bd") && c.AddrVal == AddressValueEnum.Val);
            if (audio_switch_l != -1)
            {
                if (BinList[audio_switch_l].original == 0x1)
                {
                    return;
                }
                BinList[audio_switch_l].original = 0x1;
            }
            int tempI = FindConfigData();
            //List<uint> configeHeard = new List<uint>() { 0x08, 0x0b, 0x02, 0x02, 0x01, 0x02 };
            //for (int i = 0; i < PuctHelp.TResult.Count(); i++)
            //{
            //    if (i + 6 < PuctHelp.TResult.Count()
            //         && PuctHelp.TResult[i + 0].original == configeHeard[0]
            //         && PuctHelp.TResult[i + 1].original == configeHeard[1]
            //         && PuctHelp.TResult[i + 2].original == configeHeard[2]
            //         && PuctHelp.TResult[i + 3].original == configeHeard[3]
            //         && PuctHelp.TResult[i + 4].original == configeHeard[4]
            //         && PuctHelp.TResult[i + 5].original == configeHeard[5]
            //       )
            //    {

            //        for (uint j = Convert.ToUInt32(PuctHelp.TResult[i + 0].smalladdr, 16); j < 0x60d3; j++)
            //        {
            //            if (i < PuctHelp.TResult.Count())
            //            {
            //                if (PuctHelp.TResult[i].addrsmallex.ToLower().Contains($"{j.ToString("x")}"))
            //                {
            //                    tempI++;
            //                }
            //                i++;
            //            }
            //        }
            //    }
            //}
            if (tempI == 0)
            {
               
                ShowErrorMessage("音频 开//关 未找到相应可以开启的数据 ");
                return;
            }
            var tdCount = PuctHelp.TotalDescription.Count();
            var tdTemp = tdCount + tempI;
            var wtotal_L = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad6") && c.AddrVal == AddressValueEnum.Val);
            var wtotal_H = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad7") && c.AddrVal == AddressValueEnum.Val);
            if (wtotal_L != -1)
            {
                BinList[wtotal_L].original = (byte)(tdTemp & 0xff);
            }
            if (wtotal_H != -1)
            {
                BinList[wtotal_H].original = (byte)(tdTemp >> 8 & 0xff);
            }
            var BNumI = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad8"));
            if (BNumI != -1)
            {
                BinList[BNumI].original = (byte)(BinList[BNumI].original + 0x2);
            }

        }


        private int FindConfigData()
        {
            //int tempI = 0;
            //int bLength = 0;
            List<uint> configeHeard = new List<uint>() { 0x08, 0x0b, 0x02, 0x02, 0x01, 0x02 };
            int bLength = SettingPUCT.CalculateBLength(PuctHelp.TResult, configeHeard);

            return bLength;
        }


        private  void audio_switch_en_Unchecked(object sender, RoutedEventArgs e)
        {

            if (null == BinList) return;
           
            // 执行关闭音频逻辑
            var audio_switch_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("12bd") && c.AddrVal == AddressValueEnum.Val);
            if (audio_switch_l != -1)
            {
                if (BinList[audio_switch_l].original == 0x0)
                {
                    return;
                }
                BinList[audio_switch_l].original = 0x0;
            }
            int tempI = -1;
            //描述符总长度减少
            List<uint> configeHeard = new List<uint>() { 0x08, 0x0b, 0x02, 0x02, 0x01, 0x02 };
            if (PuctHelp.TotalDescription.Count<=0)
            {
                return;
            }
            var tdCount = PuctHelp.TotalDescription.Count();
            for (int i = 0; i < tdCount; i++)
            {
                if (i + 6 < PuctHelp.TotalDescription.Count()
                      && PuctHelp.TotalDescription[i + 0].original == configeHeard[0]
                      && PuctHelp.TotalDescription[i + 1].original == configeHeard[1]
                      && PuctHelp.TotalDescription[i + 2].original == configeHeard[2]
                      && PuctHelp.TotalDescription[i + 3].original == configeHeard[3]
                      && PuctHelp.TotalDescription[i + 4].original == configeHeard[4]
                      && PuctHelp.TotalDescription[i + 5].original == configeHeard[5]
                    )
                {
                    tempI = i;
                }
            }
            if (tempI == -1)
            {
                ShowErrorMessage("音频 开//关 未找到相应可以关闭的数据 ");
                return;
            }
            var tdTemp = tdCount - (tdCount - tempI);
            var wtotal_L = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad6") && c.AddrVal == AddressValueEnum.Val);
            var wtotal_H = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad7") && c.AddrVal == AddressValueEnum.Val);
            if (wtotal_L != -1)
            {
                BinList[wtotal_L].original = (byte)(tdTemp & 0xff);
            }
            if (wtotal_H != -1)
            {
                BinList[wtotal_H].original = (byte)(tdTemp >> 8 & 0xff);
            }
            var BNumI = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("5ad8"));
            if (BNumI != -1)
            {
                BinList[BNumI].original = (byte)(BinList[BNumI].original - 0x2);
            }
            //描述符接口数量减2
            //var list =  PuctHelp.BNumInterfaces.Where(c => c.AddrVal == AddressValueEnum.Val).ToList();

        }

      
        private void ImageFlipping_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 获取选中项的索引
            int selectedIndex = ImageFlipping.SelectedIndex;

            // 更据是否存在puct 区  存在需要修改滚动的值
            if (PuctHelp.IsPuct)
            {
                Rolling_Slider.Value = selectedIndex;
            }

            if (BinList == null)
            {
                return;
            }

            if (flippingMap.ContainsKey(selectedIndex))
            {
                var audio_switch_l = BinList.FindIndex(PuctHelp.AppSetting0_0StartData, PuctHelp.AppSetting0_0Count, c => c.addrsmallex.ToLower().Contains("18ab") && c.AddrVal == AddressValueEnum.Val);
                if (audio_switch_l != -1)
                {
                    BinList[audio_switch_l].original = flippingMap[selectedIndex];
                }
            }
        }
        /// <summary>
        /// 刷新设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            USBDeviceList = new ObservableCollection<USBDeviceModel>();
            Application.Current.Dispatcher.Invoke(() =>
            {
                UpdateUSBDevices();
                if (_usbDeviceList.Count > 0)
                {
                    USBDeviceModelSelection = _usbDeviceList[(shebei.SelectedIndex == -1 ? 0 : shebei.SelectedIndex)];
                    if (!USBDeviceModelSelection.IsOpen)
                    {
                        GetDeviceInfo(USBDeviceModelSelection.DeviceNum);
                    }
                }

            });
        }
        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            IsLoading = Visibility.Visible;
            await Task.Run(() =>
            {
                try
                {
                    if (!IsUsbOpen)
                    {
                        ShowErrorMessage("请打开USB设备！！！");
                        return;
                    }
                    if (isButtonClicked)
                    {
                        return; // 如果按钮已被点击，则直接返回，不执行后续代码
                    }

                    // 将标志位设置为 true，表示按钮已被点击
                    isButtonClicked = true;

                    if (BinList == null || BinList.Count <= 0)
                    {
                        ShowErrorMessage("请先加载有效Bin文件！");
                        isButtonClicked = false;
                        return;
                    }
                    UpdateProgressBar(0);
                    var SavePath = string.Format("{0}\\Xchip_UpdateUsb_{1}.bin", AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMddHHmms"));
                    int bytesPerLine = 2;
                    string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    if (IsMsgPrint) //是否打印
                    {
                        StringBuilder originalOutput = new StringBuilder();

                        for (int i = 0; i < PuctHelp.ConfigurationDescriptorResult.Count; i += bytesPerLine)
                        {
                            StringBuilder line = new StringBuilder();

                            for (int j = i; j < i + bytesPerLine && j < PuctHelp.ConfigurationDescriptorResult.Count; j++)
                            {
                                line.Append($"{PuctHelp.ConfigurationDescriptorResult[j].original.ToString("X2")} ");
                            }

                            originalOutput.AppendLine(line.ToString());
                        }


                        string originalFilePath = System.IO.Path.Combine(desktopPath, "original.txt");

                        File.WriteAllText(originalFilePath, originalOutput.ToString());

                    }
                    AutoWhiteBalanceIsCheck();
                    UpdateProgressBar(10);
                    AutoFocusIsCheck();
                    UpdateProgressBar(20);
                    AutoExposureIsCheck();
                    //更新 Bin中Pid\Vid
                    foreach (var item in BinList)
                    {
                        if (PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.PidAddrL[PuctHelp.userParametersUsb.PidAddrL.FindIndex((c => c.sort == 0))].original;
                        }
                        if (PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.PidAddrH[PuctHelp.userParametersUsb.PidAddrH.FindIndex((c => c.sort == 0))].original;
                        }

                        if (PuctHelp.userParametersUsb.VidAddrL[PuctHelp.userParametersUsb.VidAddrL.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.VidAddrL[PuctHelp.userParametersUsb.VidAddrL.FindIndex((c => c.sort == 0))].original;
                        }
                        if (PuctHelp.userParametersUsb.VidAddrH[PuctHelp.userParametersUsb.VidAddrH.FindIndex((c => c.sort == 0))] == item)
                        {
                            item.original = PuctHelp.userParametersUsb.VidAddrH[PuctHelp.userParametersUsb.VidAddrH.FindIndex((c => c.sort == 0))].original;
                        }
                    }
                    UpdateProgressBar(30);
                    //更新 Bin中设备名称
                    //更新 Bin中Manufacture
                    //更新 Bin中SerialNumber
                    //更新 Bin中 设备名称（音频）
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.VideoMicStartIndex, PuctHelp.userParametersUsb.VideoMicEndIndex, PuctHelp.userParametersUsb.VideoMicList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.VideoStartIndex, PuctHelp.userParametersUsb.VideoEndIndex, PuctHelp.userParametersUsb.VideoList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.ManufactureStartIndex, PuctHelp.userParametersUsb.ManufactureEndIndex, PuctHelp.userParametersUsb.ManufactureList);
                    UpdateBinListWithDeviceName(PuctHelp.userParametersUsb.SerialNumberStartIndex, PuctHelp.userParametersUsb.SerialNumberEndIndex, PuctHelp.userParametersUsb.SerialNumberList);
                    UpdateProgressBar(40);
                    ///参数配置  分为两种模式 一种存在puct  一种不存在puct
                    if (PuctHelp.IsPuct)
                    {
                        UpdateBinListWithParameters(PuctHelp.PuctIndex);
                    }

                    if (PuctHelp.AppSetting0_0Count > 0 && PuctHelp.AppSetting0_0StartData > 0)
                    {
                        UpdateBinListWithControlValue(PuctHelp.PU_BRIGHTNESS_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_CONTRAST_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_HUE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_SATURATION_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_SHARPNESS_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_GAMMA_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_BACKLIGHT_COMPENSATION_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.PU_GAIN_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_FOCUS_ABSOLUTE_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_AE_MODE_CONTROL, "曝光");
                        UpdateBinListWithControlValue(PuctHelp.PU_POWER_LINE_FREQUENCY_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_ROLL_ABSOLUTE_CONTROL);

                        UpdateBinListWithControlValue(PuctHelp.PU_WHITE_BALANCE_TEMPERATURE_AUTO_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_FOCUS_AUTO_CONTROL);
                        UpdateBinListWithControlValue(PuctHelp.CT_AE_MODE_AUTO_CONTROL);
                    }
                    UpdateProgressBar(50);

                    //更新UVC拍照
                    UpdateBinListWithVideoIHDResult(PuctHelp.VideoIHDResult, PuctHelp.videoIHDStillCapture);
                    //更新Mj默认分辨率
                    //UpdateBinListWithVideoSFormatResult(PuctHelp.VideoSFormatMjpegResult, PuctHelp.videoSFormatMjpegDefaultIndex);
                    //更新YUV默认分辨率
                    //UpdateBinListWithVideoSFormatResult(PuctHelp.VideoSFormatYuvResult, PuctHelp.videoSFormatYuvDefaultIndex);
                    UpdateProgressBar(60);
                    //重新获取描述符总个数
                    SettingPUCT.GetTotalDescription(BinList);


                    ProcessVideoFTypeData();
                    if (IsMsgPrint)
                    {
                        StringBuilder LastOutput = new StringBuilder();
                        for (int i = 0; i < PuctHelp.ConfigurationDescriptorResult.Count; i += bytesPerLine)
                        {
                            StringBuilder line = new StringBuilder();

                            for (int j = i; j < i + bytesPerLine && j < PuctHelp.ConfigurationDescriptorResult.Count; j++)
                            {
                                line.Append($"{PuctHelp.ConfigurationDescriptorResult[j].original.ToString("X2")} ");
                            }

                            LastOutput.AppendLine(line.ToString());
                        }

                        string lastFilePath = System.IO.Path.Combine(desktopPath, "last.txt");
                        File.WriteAllText(lastFilePath, LastOutput.ToString());
                    }


                    //crc校验
                    UpdateBinListWithCrcCheck();

                    UpdateProgressBar(70);
                    BinHelp.BinOutFile(SavePath, BinList);


                    ShowSuccessMessage("正在写入中 请耐心等待！", 5000);
                    if (IntPtr.Size == 8)
                    {
                        bool success = XChipUSB.UsbFlashWriteFile_Old64(SavePath, 0);
                        InitializeControls(this);
                        Stopwatch stopwatch = Stopwatch.StartNew();
                        UpdateProgressBar(80);
                        while (stopwatch.ElapsedMilliseconds < 10000)
                        {
                            XChipUSB.CallBackInfo progressInfo;
                            bool result = XChipUSB.GetProgressInfo64(out progressInfo);

                            if (result)
                            {
                                int progress = progressInfo.progress;
                                int resultValue = progressInfo.result;

                                if (resultValue != 0)
                                {
                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        ShowErrorMessage($"写入失败！请重启设备！", 4000);
                                        UpdateProgressBar(0);
                                    });
                                    return;
                                }

                                if (progress == 100)
                                {
                                    // 在 UI 线程上显示成功消息和更新进度条
                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        ShowSuccessMessage($"写入成功！参考文件路径{SavePath}", 4000);

                                        BinList = null;
                                        _usbDeviceList.Clear();
                                        UpdateProgressBar(100);
                                    });
                                    return;
                                }
                            }

                            // 添加延迟，降低循环速率
                            Task.Delay(100).Wait();
                        }
                    }
                    else
                    {
                        bool success = XChipUSB.UsbFlashWriteFile_Old86(SavePath, 0);
                        InitializeControls(this);
                        Stopwatch stopwatch = Stopwatch.StartNew();
                        UpdateProgressBar(80);
                        while (stopwatch.ElapsedMilliseconds < 10000)
                        {
                            XChipUSB.CallBackInfo progressInfo;
                            bool result = XChipUSB.GetProgressInfo86(out progressInfo);

                            if (result)
                            {
                                int progress = progressInfo.progress;
                                int resultValue = progressInfo.result;

                                if (resultValue != 0)
                                {
                                    // 在 UI 线程上显示错误消息
                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        ShowErrorMessage($"写入失败！请重启设备！", 4000);
                                        UpdateProgressBar(0);
                                    });
                                    return;
                                }

                                if (progress == 100)
                                {
                                    // 在 UI 线程上显示成功消息和更新进度条
                                    Application.Current.Dispatcher.Invoke(() =>
                                    {
                                        ShowSuccessMessage($"写入成功！参考文件路径{SavePath}", 4000);

                                        BinList = null;
                                        _usbDeviceList.Clear();
                                        UpdateProgressBar(100);
                                    });
                                    
                                    return;
                                }
                            }

                            // 添加延迟，降低循环速率
                            Task.Delay(100).Wait();
                        }

                        // 在 UI 线程上显示成功消息
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            ShowSuccessMessage($"写入成功！参考文件路径{SavePath}", 4000);
                            BinList = null;
                            _usbDeviceList.Clear();
                        });
                    }
                    UpdateProgressBar(100);
                }
                catch (Exception ex)
                {
                    ShowErrorMessage(ex.Message.ToString());
                }
                finally
                {
                    IsUsbOpen = false;



                    // 将标志位设置为 false，表示按钮点击事件处理完成
                    isButtonClicked = false;

                    //ShowLoad(false);
                    _ = Task.Delay(3000).ContinueWith(_ =>
                    {
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            UpdateProgressBar(0);
                        });
                    });
                }


            });

            //ShowLoad(true);

            IsLoading = Visibility.Hidden;

          

        }


        private async Task ExecuteWithLoadingIndicatorAsync(Action action)
        {
            // 立即显示加载指示器
            IsLoading = Visibility.Visible;

            // 执行异步操作
            await Task.Run(() =>
            {
                // 使用 Dispatcher.Invoke 确保在 UI 线程上执行
                Application.Current.Dispatcher.Invoke(action);
            });
            // 添加延迟2秒钟
            await Task.Delay(2000); // 延迟2000毫秒（2秒）
            // 异步操作完成后隐藏加载指示器
            IsLoading = Visibility.Hidden;
        }


        private void ProcessVideoFTypeData()
        {
            //int bytesPerLine = 4;
            //string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            Application.Current.Dispatcher.Invoke(() =>
            {
                var videoSFormatMjpegResultIndex = -1;
                if (PuctHelp.VideoSFormatMjpegResult.Count>0)
                {
                    videoSFormatMjpegResultIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.VideoSFormatMjpegResult[0]);
                    //更新mj默认选择分辨率
                    PuctHelp.VideoSFormatMjpegResult[6].original = (byte)(mj_Combo.SelectedIndex + 1);
                }
                
                var videoSFormatYuvResultIndex = -1;
                if (PuctHelp.VideoSFormatYuvResult.Count>0)
                {
                    videoSFormatYuvResultIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.VideoSFormatYuvResult[0]);
                    //更新yuv默认选择分辨率
                    PuctHelp.VideoSFormatYuvResult[22].original = (byte)(yuv_Combo.SelectedIndex + 1);
                }
                
                
                var VsColorIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.VsColorMatchingDescriptorDescriptor[0]);

                bool mjIsFront = true;
                if (videoSFormatMjpegResultIndex == -1)
                {
                    mjIsFront = false;
                }
                else if (videoSFormatYuvResultIndex == -1)
                {
                    mjIsFront = true;
                }
                else
                {
                    mjIsFront = videoSFormatMjpegResultIndex < videoSFormatYuvResultIndex;
                }
                int mjStartIndex = 0, mjStillStartIndex = 0;
                int yuvStartIndex = 0;
                if (PuctHelp.VideoMjpegFTypes.Count>0)
                {
                    // 处理PuctHelp.VideoMjpegFTypes的数据，修改索引号
                    PuctHelp.VideoSFormatMjpegResult[4].original = (byte)PuctHelp.VideoMjpegFTypes.Count(c => !c.IsDelect);
                }
                
                List<byte> MjResult = new List<byte>();
                List<byte> stillMjResult = new List<byte>();
                stillMjResult.Add(0x0);
                stillMjResult.Add(0x24);
                stillMjResult.Add(0x03);
                stillMjResult.Add(0x00);
                stillMjResult.Add(0x0B);
                int temp = 1;
                List<string> stillList = new List<string>();
                var mjFType = PuctHelp.VideoMjpegFTypes.Where(v => !v.IsDelect && v.VideoSMjpegFTypeResult != null ).ToList();
                //添加判断是否存在两个相同的尺寸
                 var duplicates = PuctHelp.VideoMjpegFTypes.GroupBy(c => new { c.videoSMjpegFTypeWidth, c.videoSMjpegFTypeHeight })
                                                           .Where(g => g.Count() > 1).Select(g => g.Key);
                if (duplicates.Any())
                {
                    // 对于每个重复的宽度和高度组合，找出具有最大videoSMjpegFTypeIndex的项
                    var maxIndexItem = mjFType
                        .Where(item => item.videoSMjpegFTypeWidth == duplicates.First().videoSMjpegFTypeWidth
                                    && item.videoSMjpegFTypeHeight == duplicates.First().videoSMjpegFTypeHeight)
                        .OrderByDescending(item => item.videoSMjpegFTypeIndex)
                        .FirstOrDefault();
                    if (maxIndexItem != null)
                    {
                        var selectedItem = mjFType.FirstOrDefault(c => c.VideoMjpegName == (mj_Combo.SelectedItem as VideoMjpegFType).VideoMjpegName);

                        if (selectedItem != null)
                        {
                            //替换mjFtype中的等于搞和宽和索引的 里面的数据
                            foreach (var item in mjFType)
                            {
                                if (item.videoSMjpegFTypeHeight == maxIndexItem.videoSMjpegFTypeHeight &&
                                    item.videoSMjpegFTypeIndex == maxIndexItem.videoSMjpegFTypeIndex &&
                                    item.videoSMjpegFTypeWidth == maxIndexItem.videoSMjpegFTypeWidth)
                                {
                                    var videoYuvIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == item.VideoSMjpegFTypeResult[0]);

                                    for (int i = 5; i < selectedItem.VideoSMjpegFTypeResult.Count; i++)
                                    {
                                        PuctHelp.ConfigurationDescriptorResult[videoYuvIndex + i].original = selectedItem.VideoSMjpegFTypeResult[i].original;
                                    }

                                }
                            }
                        }

                    }

                }
                foreach (var videoMjpegFType in mjFType)
                {
                    videoMjpegFType.VideoSMjpegFTypeResult[3].original = (byte)temp++;
                    MjResult.AddRange(videoMjpegFType.VideoSMjpegFTypeResult.Select(c => c.original));

                    if (!stillList.Contains(videoMjpegFType.VideoMjpegName))
                    {
                        stillList.Add(videoMjpegFType.VideoMjpegName);
                        stillMjResult.Add((byte)((videoMjpegFType.videoSMjpegFTypeWidth >> 0) & 0xFF));
                        stillMjResult.Add((byte)((videoMjpegFType.videoSMjpegFTypeWidth >> 8) & 0xFF));
                        stillMjResult.Add((byte)((videoMjpegFType.videoSMjpegFTypeHeight >> 0) & 0xFF));
                        stillMjResult.Add((byte)((videoMjpegFType.videoSMjpegFTypeHeight >> 8) & 0xFF));
                    }
                }

                stillMjResult.Add(0x0);
                stillMjResult[0] = (byte)stillMjResult.Count;
                stillMjResult[4] = (byte)stillList.Count;

                //这里需要判断有没有截图功能，没有就不加入
                if (mjIsFront && PuctHelp.StillImageFrameTypeResultOne.Count > 0)
                {
                    MjResult.AddRange(stillMjResult);
                }
                else
                {
                    if (!mjIsFront && PuctHelp.StillImageFrameTypeResultTwo.Count > 0)
                    {
                        MjResult.AddRange(stillMjResult);
                    }
                }

                // 处理PuctHelp.VideoYuvFTypes的数据，修改索引号
                if (PuctHelp.VideoYuvFTypes.Count>0)
                {
                    PuctHelp.VideoSFormatYuvResult[4].original = (byte)PuctHelp.VideoYuvFTypes.Count(c => !c.IsDelect);
                }

                
                temp = 1;
                List<byte> YuvResult = new List<byte>();
                List<byte> stillYuvResult = new List<byte>();
                stillYuvResult.Add(0x0);
                stillYuvResult.Add(0x24);
                stillYuvResult.Add(0x03);
                stillYuvResult.Add(0x00);
                stillYuvResult.Add(0x0B);
                stillList = new List<string>();
                var yuvFType = PuctHelp.VideoYuvFTypes.Where(v => !v.IsDelect && v.VideoSYuvFTypeResult != null);

                //添加判断是否存在两个相同的尺寸
               var yuvlicates = PuctHelp.VideoYuvFTypes.GroupBy(c => new { c.videoSYuvFTypeWidth, c.videoSYuvFTypeHeight })
                                                          .Where(g => g.Count() > 1).Select(g => g.Key);
                if (yuvlicates.Any())
                {
                    // 对于每个重复的宽度和高度组合，找出具有最大videoSMjpegFTypeIndex的项
                    var maxIndexItem = yuvFType
                        .Where(item => item.videoSYuvFTypeWidth == yuvlicates.First().videoSYuvFTypeWidth
                                    && item.videoSYuvFTypeHeight == yuvlicates.First().videoSYuvFTypeHeight)
                        .OrderByDescending(item => item.videoSYuvFTypeIndex)
                        .FirstOrDefault();
                    if (maxIndexItem != null)
                    {
                        var selectedItem = yuvFType.FirstOrDefault(c => c.VideoYuvName == (yuv_Combo.SelectedItem as VideoYuvFType).VideoYuvName);

                        if (selectedItem !=null)
                        {
                            //替换mjFtype中的等于搞和宽和索引的 里面的数据
                            foreach (var item in yuvFType)
                            {
                                if (item.videoSYuvFTypeHeight == maxIndexItem.videoSYuvFTypeHeight &&
                                    item.videoSYuvFTypeIndex == maxIndexItem.videoSYuvFTypeIndex &&
                                    item.videoSYuvFTypeWidth == maxIndexItem.videoSYuvFTypeWidth)
                                {
                                    var videoYuvIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == item.VideoSYuvFTypeResult[0]);

                                    for (int i = 5; i < selectedItem.VideoSYuvFTypeResult.Count; i++)
                                    {
                                        PuctHelp.ConfigurationDescriptorResult[videoYuvIndex + i].original = selectedItem.VideoSYuvFTypeResult[i].original;
                                    }

                                }
                            }
                        }
                        
                    }

                }


                foreach (var videoYuvFType in yuvFType)
                {
                    videoYuvFType.VideoSYuvFTypeResult[3].original = (byte)temp++;
                    YuvResult.AddRange(videoYuvFType.VideoSYuvFTypeResult.Select(c => c.original));

                    if (!stillList.Contains(videoYuvFType.VideoYuvName))
                    {
                        stillList.Add(videoYuvFType.VideoYuvName);
                        stillYuvResult.Add((byte)((videoYuvFType.videoSYuvFTypeWidth >> 0) & 0xFF));
                        stillYuvResult.Add((byte)((videoYuvFType.videoSYuvFTypeWidth >> 8) & 0xFF));
                        stillYuvResult.Add((byte)((videoYuvFType.videoSYuvFTypeHeight >> 0) & 0xFF));
                        stillYuvResult.Add((byte)((videoYuvFType.videoSYuvFTypeHeight >> 8) & 0xFF));
                    }
                }

                stillYuvResult.Add(0x0);
                stillYuvResult[0] = (byte)stillYuvResult.Count;
                stillYuvResult[4] = (byte)stillList.Count;

                //这里需要判断有没有截图功能
                if (mjIsFront && PuctHelp.StillImageFrameTypeResultTwo.Count > 0)
                {
                    YuvResult.AddRange(stillYuvResult);
                }
                else
                {
                    if (!mjIsFront && PuctHelp.StillImageFrameTypeResultOne.Count > 0)
                    {
                        YuvResult.AddRange(stillYuvResult);
                    }
                }

                if (mjIsFront)
                {
                    mjStartIndex = PuctHelp.ConfigurationDescriptorResult[videoSFormatMjpegResultIndex].original + videoSFormatMjpegResultIndex;
                    // 更新MJPEG相关的描述信息
                    UpdateMjpegDescriptorInfo(MjResult, ref mjStartIndex, ref mjStillStartIndex, VsColorIndex);
                    if (videoSFormatYuvResultIndex != -1)
                    {
                        yuvStartIndex = PuctHelp.ConfigurationDescriptorResult[videoSFormatYuvResultIndex].original + videoSFormatYuvResultIndex;
                        //添加yuv 描述信息头部
                        for (int i = videoSFormatYuvResultIndex; i < yuvStartIndex; i++)
                        {
                            PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = PuctHelp.ConfigurationDescriptorResult[i].original;
                            mjStartIndex++;
                        }
                        
                    }
                    // 更新YUV相关的描述信息
                    UpdateYuvDescriptorInfo(YuvResult,ref mjStartIndex, VsColorIndex);

                }
                else
                {
                    yuvStartIndex = PuctHelp.ConfigurationDescriptorResult[videoSFormatYuvResultIndex].original + videoSFormatYuvResultIndex;
                    // 更新YUV相关的描述信息
                    UpdateYuvDescriptorInfo(YuvResult, ref yuvStartIndex);

                    if (videoSFormatMjpegResultIndex !=-1)
                    {
                        //int videoSFormatMjpegResultIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.VideoSFormatMjpegResult[0]);
                         mjStartIndex = PuctHelp.ConfigurationDescriptorResult[videoSFormatMjpegResultIndex].original + videoSFormatMjpegResultIndex;
                        // 添加 MJ 描述信息头部
                        for (int i = videoSFormatMjpegResultIndex; i < mjStartIndex; i++)
                        {
                            PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = PuctHelp.ConfigurationDescriptorResult[i].original;
                            yuvStartIndex++;
                        }
                    }

                    // 更新MJPEG相关的描述信息
                    UpdateMjpegDescriptorInfo(MjResult, ref yuvStartIndex, VsColorIndex);
                        
                    
                    mjStartIndex = yuvStartIndex;
                }
                //var VihdCount = PuctHelp.videoIHDTotal - (PuctHelp.ConfigurationDescriptorResult.Count - mjStartIndex);
                int dataClear = 0;
                //把后面的数据清空成0x0
                for (int i = mjStartIndex; i < PuctHelp.ConfigurationDescriptorResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[i].original = 0x0;
                    dataClear++;
                }
                // 更新IHD相关信息
                UpdateIhdInfo(mjStartIndex);

                // 更新长度信息
                UpdateLengthInfo(mjStartIndex, dataClear);
            });
        }


        private void UpdateMjpegDescriptorInfo(List<byte> MjResult, ref int yuvStartIndex,int VsColorIndex)
        {

            
            
           

            int mjStillStartIndex = -1;

            if (PuctHelp.StillImageFrameTypeResultTwo.Count > 0)
            {
                mjStillStartIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.StillImageFrameTypeResultTwo[0]);
            }

            if (mjStillStartIndex != -1)
            {
                var mjEnd = PuctHelp.ConfigurationDescriptorResult[mjStillStartIndex].original + mjStillStartIndex;
                var mjEndCount = PuctHelp.ConfigurationDescriptorResult.Count - mjEnd;
                if (MjResult.Count > 0)
                {
                    for (int i = 0; i < MjResult.Count; i++)
                    {
                        PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = MjResult[i];
                        yuvStartIndex++;
                    }
                }
               
            }
            else
            {
                for (int i = 0; i < MjResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = MjResult[i];
                    yuvStartIndex++;
                }
                
            }
           
            if (VsColorIndex > 0)
            {
                for (int i = VsColorIndex; i < PuctHelp.ConfigurationDescriptorResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = PuctHelp.ConfigurationDescriptorResult[i].original;
                    yuvStartIndex++;
                }
            }
        }


        private void UpdateMjpegDescriptorInfo(List<byte> MjResult, ref int mjStartIndex, ref int mjStillStartIndex, int VsColorIndex)
        {
            if (PuctHelp.StillImageFrameTypeResultOne.Count > 0)
            {
                mjStillStartIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.StillImageFrameTypeResultOne[0]);
            }

            if (mjStillStartIndex != -1)
            {
                var mjEnd = PuctHelp.ConfigurationDescriptorResult[mjStillStartIndex].original + mjStillStartIndex;
                if (MjResult.Count > 0)
                {
                    for (int i = 0; i < MjResult.Count; i++)
                    {
                        PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = MjResult[i];
                        mjStartIndex++;
                    }
                }
            }
            else
            {
                for (int i = 0; i < MjResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = MjResult[i];
                    mjStartIndex++;
                }
            }
        }


        private void UpdateYuvDescriptorInfo(List<byte> YuvResult,ref int yuvStartIndex)
        {
            int yuvStillStartIndex = -1;

            if (PuctHelp.StillImageFrameTypeResultOne.Count > 0)
            {
                yuvStillStartIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.StillImageFrameTypeResultOne[0]);
            }

            if (yuvStillStartIndex != -1)
            {
                var yuvEnd = PuctHelp.ConfigurationDescriptorResult[yuvStillStartIndex].original + yuvStillStartIndex;
                if (YuvResult.Count > 0)
                {
                    for (int i = 0; i < YuvResult.Count; i++)
                    {
                        PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = YuvResult[i];
                        yuvStartIndex++;
                    }
                }
            }
            else
            {
                for (int i = 0; i < YuvResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[yuvStartIndex].original = YuvResult[i];
                    yuvStartIndex++;
                }
            }
        }


        private void UpdateYuvDescriptorInfo(List<byte> YuvResult,ref  int mjStartIndex,int VsColorIndex)
        {
            int yuvStillStartIndex = -1;
            if (PuctHelp.StillImageFrameTypeResultTwo.Count > 0)
            {
                yuvStillStartIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.StillImageFrameTypeResultTwo[0]);
            }


            if (yuvStillStartIndex != -1)
            {
                var yuvEnd = PuctHelp.ConfigurationDescriptorResult[yuvStillStartIndex].original + yuvStillStartIndex;
                var yuvEndCount = PuctHelp.ConfigurationDescriptorResult.Count - yuvEnd;
                if (YuvResult.Count > 0)
                {
                    for (int i = 0; i < YuvResult.Count; i++)
                    {
                        PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = YuvResult[i];
                        mjStartIndex++;
                    }
                }
                
            }
            else
            {
                for (int i = 0; i < YuvResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = YuvResult[i];
                    mjStartIndex++;
                }
               
            }
           
            if (VsColorIndex > 0)
            {
                for (int i = VsColorIndex; i < PuctHelp.ConfigurationDescriptorResult.Count; i++)
                {
                    PuctHelp.ConfigurationDescriptorResult[mjStartIndex].original = PuctHelp.ConfigurationDescriptorResult[i].original;
                    mjStartIndex++;
                }
            }
        }





        private void UpdateIhdInfo(int mjStartIndex)
        {
            if (PuctHelp.VideoIHDResult.Count>0)
            {
                var videoIHDResultIndex = PuctHelp.ConfigurationDescriptorResult.FindIndex(c => c == PuctHelp.VideoIHDResult[4]);
                int VihdCount = PuctHelp.videoIHDTotal - (PuctHelp.ConfigurationDescriptorResult.Count - mjStartIndex);
                PuctHelp.ConfigurationDescriptorResult[videoIHDResultIndex].original = (byte)((VihdCount >> 0) & 0xFF);
                PuctHelp.ConfigurationDescriptorResult[videoIHDResultIndex + 1].original = (byte)((VihdCount >> 8) & 0xFF);
            }
            
        }

        private void UpdateLengthInfo( int yuvStartIndex,int dataClear)
        {
            int Length = (PuctHelp.ConfigurationDescriptorResult[3].original << 8) | PuctHelp.ConfigurationDescriptorResult[2].original;
            int videoLength = FindConfigData();
            if ((bool)audio_switch_en.IsChecked)
            {
                //int lengthData = Length > (yuvStartIndex + videoLength) ? yuvStartIndex + videoLength : Length;

                PuctHelp.ConfigurationDescriptorResult[2].original = (byte)(yuvStartIndex & 0xFF);
                PuctHelp.ConfigurationDescriptorResult[3].original = (byte)((yuvStartIndex >> 8) & 0xFF);
                
            }
            else
            {
                int lengthData = Length > (yuvStartIndex - videoLength) ? Length - dataClear : yuvStartIndex - videoLength;
                PuctHelp.ConfigurationDescriptorResult[2].original = (byte)(lengthData & 0xFF);
                PuctHelp.ConfigurationDescriptorResult[3].original = (byte)((lengthData >> 8) & 0xFF);
            }
        }




        private void HandleAutoIncrementCheckbox(TextBox textBox, CheckBox checkBox)
        {
            if (textBox != null && textBox.Text.Length > 0 && checkBox.IsChecked.GetValueOrDefault())
            {
                string input = textBox.Text.Trim();
                Match match = Regex.Match(input, @"\d+$");
                if (match.Success)
                {
                  
                        int number = int.Parse(match.Value);
                        string leadingZeros = new string('0', match.Value.Length - number.ToString().Length);
                        textBox.Text = input.Substring(0, match.Index) + leadingZeros + (number + 1);
                 
                    
                }
                else
                {
                    textBox.Text += '0';
                }
            }
        }
        /// <summary>
        /// 设备名称勾选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserDevicCheck_Checked(object sender, RoutedEventArgs e)
        {
            HandleAutoIncrementCheckbox(UserDevice, UserDevicCheck);

        }
        /// <summary>
        /// iManufacture 勾选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserManuCheck_Checked(object sender, RoutedEventArgs e)
        {
            HandleAutoIncrementCheckbox(UserManufacture, UserManuCheck);
        }
        /// <summary>
        /// iSerialNumber 勾选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserSerialCheck_Checked(object sender, RoutedEventArgs e)
        {
            HandleAutoIncrementCheckbox(UserSerialNumber, UserSerialCheck);
        }
        /// <summary>
        /// 设备名称（音频） 勾选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserMicCheck_Checked(object sender, RoutedEventArgs e)
        {
            HandleAutoIncrementCheckbox(UserMic, UserMicCheck);
        }

        private void MjpegBtn_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            VideoMjpegFType videoMjpeg = (VideoMjpegFType)button.Tag;
            if (videoMjpeg != null && !mj_ListBox.SelectedItems.Contains(videoMjpeg))
            {
                if (PuctHelp.VideoMjpegFTypes.Count(c => c.VideoMjpegName == videoMjpeg.VideoMjpegName) > 1)
                {
                    ShowErrorMessage($"当前视频流 {videoMjpeg.VideoMjpegName} 正在使用默认尺寸设置，因此不支持直接删除。请先修改该视频流的尺寸设置，使其不再是默认尺寸，然后再尝试删除操作。谢谢！",4000);
                    return;
                }
                // 执行删除操作
                PuctHelp.VideoMjpegFTypes.ForEach(c => {
                    if (c == videoMjpeg)
                    {
                        c.IsDelect = true;
                    }
                });
                var list = PuctHelp.VideoMjpegFTypes.Where(v => (v.videoSMjpegFTypeWidth != 0 || v.videoSMjpegFTypeHeight != 0) && v.IsDelect == false ).ToList();
                var uniqueList = list.GroupBy(v => new { v.videoSMjpegFTypeWidth, v.videoSMjpegFTypeHeight })
                                     .Select(g => g.OrderBy(v => v.videoSMjpegFTypeIndex).First()).ToList();
                // 修改索引获取逻辑
                var mj = mj_Combo.SelectedValue as VideoMjpegFType;
                int selectedIndex = list.FindIndex(c => c == mj);
                if (selectedIndex >= 0)
                {
                    mj_Combo.ItemsSource = uniqueList;
                    mj_Combo.SelectedIndex = selectedIndex;
                    mj_ListBox.ItemsSource = uniqueList;
                    mj_ListBox.SelectedIndex = selectedIndex;
                }
                else
                {
                    // 如果原索引不在列表中，则默认选择第一个元素
                    mj_Combo.ItemsSource = uniqueList;
                    mj_Combo.SelectedIndex = 0;
                    mj_ListBox.ItemsSource = uniqueList;
                    mj_ListBox.SelectedIndex = 0;
                }

                
            }
        }

        private void YuvBtn_Click(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            VideoYuvFType videoYuv = (VideoYuvFType)button.Tag;
            if (videoYuv != null && !yuv_ListBox.SelectedItems.Contains(videoYuv))
            {
                if (PuctHelp.VideoYuvFTypes.Count(c => c.VideoYuvName == videoYuv.VideoYuvName)>1)
                {
                    ShowErrorMessage($"当前视频流 {videoYuv.VideoYuvName} 正在使用默认尺寸设置，因此不支持直接删除。请先修改该视频流的尺寸设置，使其不再是默认尺寸，然后再尝试删除操作。谢谢！", 4000);
                    return;
                } 

                // 执行删除操作
                //PuctHelp.VideoYuvFTypes.Find(c => c == videoYuv).IsDelect = true;
                PuctHelp.VideoYuvFTypes.ForEach(c => {
                    if (c == videoYuv)
                    {
                        c.IsDelect = true;
                    }
                });
                var list = PuctHelp.VideoYuvFTypes.Where(v => (v.videoSYuvFTypeWidth != 0 || v.videoSYuvFTypeHeight != 0) && v.IsDelect == false ).ToList();
                var uniqueList = list.GroupBy(v => new { v.videoSYuvFTypeWidth, v.videoSYuvFTypeHeight })
                                     .Select(g => g.OrderBy(v => v.videoSYuvFTypeIndex).First()).ToList();

                // 修改索引获取逻辑
                var mj = yuv_Combo.SelectedValue as VideoYuvFType;
                int selectedIndex = list.FindIndex(c => c == mj);
                if (selectedIndex >= 0)
                {
                    yuv_Combo.ItemsSource = uniqueList;
                    yuv_Combo.SelectedIndex = selectedIndex;
                    yuv_ListBox.ItemsSource = uniqueList;
                    yuv_ListBox.SelectedIndex = selectedIndex;
                }
                else
                {
                    // 如果原索引不在列表中，则默认选择第一个元素
                    yuv_Combo.ItemsSource = uniqueList;
                    yuv_Combo.SelectedIndex = 0;
                    yuv_ListBox.ItemsSource = uniqueList;
                    yuv_ListBox.SelectedIndex = 0;
                }

            }

        }

        private void yuv_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = (ListBox)sender;
            VideoYuvFType selectedYuv = (VideoYuvFType)listBox.SelectedItem;
            if (selectedYuv != null)
            {
                yuv_Combo.SelectedItem = selectedYuv;
            }
        }

        private void mj_ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listBox = (ListBox)sender;
            VideoMjpegFType selectedMjpeg = (VideoMjpegFType)listBox.SelectedItem;
            if (selectedMjpeg != null)
            {
                mj_Combo.SelectedItem = selectedMjpeg;
            }
        }
    }
}
